DonorsChoose

DonorsChoose.org receives hundreds of thousands of project proposals each year for classroom projects in need of funding. Right now, a large number of volunteers is needed to manually screen each submission before it's approved to be posted on the DonorsChoose.org website.

Next year, DonorsChoose.org expects to receive close to 500,000 project proposals. As a result, there are three main problems they need to solve:

  • How to scale current manual processes and resources to screen 500,000 projects so that they can be posted as quickly and as efficiently as possible
  • How to increase the consistency of project vetting across different volunteers to improve the experience for teachers
  • How to focus volunteer time on the applications that need the most assistance

The goal of the competition is to predict whether or not a DonorsChoose.org project proposal submitted by a teacher will be approved, using the text of project descriptions as well as additional metadata about the project, teacher, and school. DonorsChoose.org can then use this information to identify projects most likely to need further review before approval.

About the DonorsChoose Data Set

The train.csv data set provided by DonorsChoose contains the following features:

Feature Description
project_id A unique identifier for the proposed project. Example: p036502
project_title Title of the project. Examples:
  • Art Will Make You Happy!
  • First Grade Fun
project_grade_category Grade level of students for which the project is targeted. One of the following enumerated values:
  • Grades PreK-2
  • Grades 3-5
  • Grades 6-8
  • Grades 9-12
project_subject_categories One or more (comma-separated) subject categories for the project from the following enumerated list of values:
  • Applied Learning
  • Care & Hunger
  • Health & Sports
  • History & Civics
  • Literacy & Language
  • Math & Science
  • Music & The Arts
  • Special Needs
  • Warmth

Examples:
  • Music & The Arts
  • Literacy & Language, Math & Science
school_state State where school is located (Two-letter U.S. postal code). Example: WY
project_subject_subcategories One or more (comma-separated) subject subcategories for the project. Examples:
  • Literacy
  • Literature & Writing, Social Sciences
project_resource_summary An explanation of the resources needed for the project. Example:
  • My students need hands on literacy materials to manage sensory needs!
project_essay_1 First application essay*
project_essay_2 Second application essay*
project_essay_3 Third application essay*
project_essay_4 Fourth application essay*
project_submitted_datetime Datetime when project application was submitted. Example: 2016-04-28 12:43:56.245
teacher_id A unique identifier for the teacher of the proposed project. Example: bdf8baa8fedef6bfeec7ae4ff1c15c56
teacher_prefix Teacher's title. One of the following enumerated values:
  • nan
  • Dr.
  • Mr.
  • Mrs.
  • Ms.
  • Teacher.
teacher_number_of_previously_posted_projects Number of project applications previously submitted by the same teacher. Example: 2

* See the section Notes on the Essay Data for more details about these features.

Additionally, the resources.csv data set provides more data about the resources required for each project. Each line in this file represents a resource required by a project:

Feature Description
id A project_id value from the train.csv file. Example: p036502
description Desciption of the resource. Example: Tenor Saxophone Reeds, Box of 25
quantity Quantity of the resource required. Example: 3
price Price of the resource required. Example: 9.95

Note: Many projects require multiple resources. The id value corresponds to a project_id in train.csv, so you use it as a key to retrieve all resources needed for a project:

The data set contains the following label (the value you will attempt to predict):

Label Description
project_is_approved A binary flag indicating whether DonorsChoose approved the project. A value of 0 indicates the project was not approved, and a value of 1 indicates the project was approved.

Notes on the Essay Data

    Prior to May 17, 2016, the prompts for the essays were as follows:
  • __project_essay_1:__ "Introduce us to your classroom"
  • __project_essay_2:__ "Tell us more about your students"
  • __project_essay_3:__ "Describe how your students will use the materials you're requesting"
  • __project_essay_3:__ "Close by sharing why your project will make a difference"
    Starting on May 17, 2016, the number of essays was reduced from 4 to 2, and the prompts for the first 2 essays were changed to the following:
  • __project_essay_1:__ "Describe your students: What makes your students special? Specific details about their background, your neighborhood, and your school are all helpful."
  • __project_essay_2:__ "About your project: How will these materials make a difference in your students' learning and improve their school lives?"

  • For all projects with project_submitted_datetime of 2016-05-17 and later, the values of project_essay_3 and project_essay_4 will be NaN.
In [1]:
%%time

%matplotlib inline
import warnings
warnings.filterwarnings("ignore")

import sqlite3
import math
import pandas as pd
import numpy as np
import nltk
import string
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import TfidfVectorizer

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import confusion_matrix
from sklearn import metrics
from sklearn.metrics import roc_curve, auc
from nltk.stem.porter import PorterStemmer

import re
# Tutorial about Python regular expressions: https://pymotw.com/2/re/
import string
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.stem.wordnet import WordNetLemmatizer

from gensim.models import Word2Vec
from gensim.models import KeyedVectors
import pickle

from tqdm import tqdm
import os

from plotly import plotly
import plotly.offline as offline
import plotly.graph_objs as go
offline.init_notebook_mode()
from collections import Counter
Wall time: 1min 20s

1.1 Reading Data

In [2]:
# using 40k rows due to memory constraint

project_data = pd.read_csv('train_data.csv',nrows=40000)
resource_data = pd.read_csv('resources.csv')
In [3]:
print("Number of data points in train data", project_data.shape)
print('-'*50)
print("The attributes of data :", project_data.columns.values)
Number of data points in train data (40000, 17)
--------------------------------------------------
The attributes of data : ['Unnamed: 0' 'id' 'teacher_id' 'teacher_prefix' 'school_state'
 'project_submitted_datetime' 'project_grade_category'
 'project_subject_categories' 'project_subject_subcategories'
 'project_title' 'project_essay_1' 'project_essay_2' 'project_essay_3'
 'project_essay_4' 'project_resource_summary'
 'teacher_number_of_previously_posted_projects' 'project_is_approved']
In [4]:
print("Number of data points in train data", resource_data.shape)
print(resource_data.columns.values)
resource_data.head(2)
Number of data points in train data (1541272, 4)
['id' 'description' 'quantity' 'price']
Out[4]:
id description quantity price
0 p233245 LC652 - Lakeshore Double-Space Mobile Drying Rack 1 149.00
1 p069063 Bouncy Bands for Desks (Blue support pipes) 3 14.95

1.2 preprocessing of project_subject_categories

In [5]:
catogories = list(project_data['project_subject_categories'].values)
# remove special characters from list of strings python: https://stackoverflow.com/a/47301924/4084039

# https://www.geeksforgeeks.org/removing-stop-words-nltk-python/
# https://stackoverflow.com/questions/23669024/how-to-strip-a-specific-word-from-a-string
# https://stackoverflow.com/questions/8270092/remove-all-whitespace-in-a-string-in-python
cat_list = []
for i in catogories:
    temp = ""
    # consider we have text like this "Math & Science, Warmth, Care & Hunger"
    for j in i.split(','): # it will split it in three parts ["Math & Science", "Warmth", "Care & Hunger"]
        if 'The' in j.split(): # this will split each of the catogory based on space "Math & Science"=> "Math","&", "Science"
            j=j.replace('The','') # if we have the words "The" we are going to replace it with ''(i.e removing 'The')
        j = j.replace(' ','') # we are placeing all the ' '(space) with ''(empty) ex:"Math & Science"=>"Math&Science"
        temp+=j.strip()+" " #" abc ".strip() will return "abc", remove the trailing spaces
        temp = temp.replace('&','_') # we are replacing the & value into 
    cat_list.append(temp.strip())
    
project_data['clean_categories'] = cat_list
project_data.drop(['project_subject_categories'], axis=1, inplace=True)

from collections import Counter
my_counter = Counter()
for word in project_data['clean_categories'].values:
    my_counter.update(word.split())

cat_dict = dict(my_counter)
sorted_cat_dict = dict(sorted(cat_dict.items(), key=lambda kv: kv[1]))

1.3 preprocessing of project_subject_subcategories

In [6]:
sub_catogories = list(project_data['project_subject_subcategories'].values)
# remove special characters from list of strings python: https://stackoverflow.com/a/47301924/4084039

# https://www.geeksforgeeks.org/removing-stop-words-nltk-python/
# https://stackoverflow.com/questions/23669024/how-to-strip-a-specific-word-from-a-string
# https://stackoverflow.com/questions/8270092/remove-all-whitespace-in-a-string-in-python

sub_cat_list = []
for i in sub_catogories:
    temp = ""
    # consider we have text like this "Math & Science, Warmth, Care & Hunger"
    for j in i.split(','): # it will split it in three parts ["Math & Science", "Warmth", "Care & Hunger"]
        if 'The' in j.split(): # this will split each of the catogory based on space "Math & Science"=> "Math","&", "Science"
            j=j.replace('The','') # if we have the words "The" we are going to replace it with ''(i.e removing 'The')
        j = j.replace(' ','') # we are placeing all the ' '(space) with ''(empty) ex:"Math & Science"=>"Math&Science"
        temp +=j.strip()+" "#" abc ".strip() will return "abc", remove the trailing spaces
        temp = temp.replace('&','_')
    sub_cat_list.append(temp.strip())

project_data['clean_subcategories'] = sub_cat_list
project_data.drop(['project_subject_subcategories'], axis=1, inplace=True)

# count of all the words in corpus python: https://stackoverflow.com/a/22898595/4084039
my_counter = Counter()
for word in project_data['clean_subcategories'].values:
    my_counter.update(word.split())
    
sub_cat_dict = dict(my_counter)
sorted_sub_cat_dict = dict(sorted(sub_cat_dict.items(), key=lambda kv: kv[1]))

1.3 Text preprocessing

In [7]:
# merge two column text dataframe: 
project_data["essay"] = project_data["project_essay_1"].map(str) +\
                        project_data["project_essay_2"].map(str) + \
                        project_data["project_essay_3"].map(str) + \
                        project_data["project_essay_4"].map(str)
In [8]:
project_data.head(2)
Out[8]:
Unnamed: 0 id teacher_id teacher_prefix school_state project_submitted_datetime project_grade_category project_title project_essay_1 project_essay_2 project_essay_3 project_essay_4 project_resource_summary teacher_number_of_previously_posted_projects project_is_approved clean_categories clean_subcategories essay
0 160221 p253737 c90749f5d961ff158d4b4d1e7dc665fc Mrs. IN 2016-12-05 13:43:57 Grades PreK-2 Educational Support for English Learners at Home My students are English learners that are work... \"The limits of your language are the limits o... NaN NaN My students need opportunities to practice beg... 0 0 Literacy_Language ESL Literacy My students are English learners that are work...
1 140945 p258326 897464ce9ddc600bced1151f324dd63a Mr. FL 2016-10-25 09:22:10 Grades 6-8 Wanted: Projector for Hungry Learners Our students arrive to our school eager to lea... The projector we need for our school is very c... NaN NaN My students need a projector to help with view... 7 1 History_Civics Health_Sports Civics_Government TeamSports Our students arrive to our school eager to lea...
In [9]:
#### 1.4.2.3 Using Pretrained Models: TFIDF weighted W2V
In [10]:
# printing some random reviews
print(project_data['essay'].values[0])
print("="*50)
print(project_data['essay'].values[150])
print("="*50)
print(project_data['essay'].values[1000])
print("="*50)
print(project_data['essay'].values[20000])
print("="*50)
My students are English learners that are working on English as their second or third languages. We are a melting pot of refugees, immigrants, and native-born Americans bringing the gift of language to our school. \r\n\r\n We have over 24 languages represented in our English Learner program with students at every level of mastery.  We also have over 40 countries represented with the families within our school.  Each student brings a wealth of knowledge and experiences to us that open our eyes to new cultures, beliefs, and respect.\"The limits of your language are the limits of your world.\"-Ludwig Wittgenstein  Our English learner's have a strong support system at home that begs for more resources.  Many times our parents are learning to read and speak English along side of their children.  Sometimes this creates barriers for parents to be able to help their child learn phonetics, letter recognition, and other reading skills.\r\n\r\nBy providing these dvd's and players, students are able to continue their mastery of the English language even if no one at home is able to assist.  All families with students within the Level 1 proficiency status, will be a offered to be a part of this program.  These educational videos will be specially chosen by the English Learner Teacher and will be sent home regularly to watch.  The videos are to help the child develop early reading skills.\r\n\r\nParents that do not have access to a dvd player will have the opportunity to check out a dvd player to use for the year.  The plan is to use these videos and educational dvd's for the years to come for other EL students.\r\nnannan
==================================================
The 51 fifth grade students that will cycle through my classroom this year all love learning, at least most of the time. At our school, 97.3% of the students receive free or reduced price lunch. Of the 560 students, 97.3% are minority students. \r\nThe school has a vibrant community that loves to get together and celebrate. Around Halloween there is a whole school parade to show off the beautiful costumes that students wear. On Cinco de Mayo we put on a big festival with crafts made by the students, dances, and games. At the end of the year the school hosts a carnival to celebrate the hard work put in during the school year, with a dunk tank being the most popular activity.My students will use these five brightly colored Hokki stools in place of regular, stationary, 4-legged chairs. As I will only have a total of ten in the classroom and not enough for each student to have an individual one, they will be used in a variety of ways. During independent reading time they will be used as special chairs students will each use on occasion. I will utilize them in place of chairs at my small group tables during math and reading times. The rest of the day they will be used by the students who need the highest amount of movement in their life in order to stay focused on school.\r\n\r\nWhenever asked what the classroom is missing, my students always say more Hokki Stools. They can't get their fill of the 5 stools we already have. When the students are sitting in group with me on the Hokki Stools, they are always moving, but at the same time doing their work. Anytime the students get to pick where they can sit, the Hokki Stools are the first to be taken. There are always students who head over to the kidney table to get one of the stools who are disappointed as there are not enough of them. \r\n\r\nWe ask a lot of students to sit for 7 hours a day. The Hokki stools will be a compromise that allow my students to do desk work and move at the same time. These stools will help students to meet their 60 minutes a day of movement by allowing them to activate their core muscles for balance while they sit. For many of my students, these chairs will take away the barrier that exists in schools for a child who can't sit still.nannan
==================================================
How do you remember your days of school? Was it in a sterile environment with plain walls, rows of desks, and a teacher in front of the room? A typical day in our room is nothing like that. I work hard to create a warm inviting themed room for my students look forward to coming to each day.\r\n\r\nMy class is made up of 28 wonderfully unique boys and girls of mixed races in Arkansas.\r\nThey attend a Title I school, which means there is a high enough percentage of free and reduced-price lunch to qualify. Our school is an \"open classroom\" concept, which is very unique as there are no walls separating the classrooms. These 9 and 10 year-old students are very eager learners; they are like sponges, absorbing all the information and experiences and keep on wanting more.With these resources such as the comfy red throw pillows and the whimsical nautical hanging decor and the blue fish nets, I will be able to help create the mood in our classroom setting to be one of a themed nautical environment. Creating a classroom environment is very important in the success in each and every child's education. The nautical photo props will be used with each child as they step foot into our classroom for the first time on Meet the Teacher evening. I'll take pictures of each child with them, have them developed, and then hung in our classroom ready for their first day of 4th grade.  This kind gesture will set the tone before even the first day of school! The nautical thank you cards will be used throughout the year by the students as they create thank you cards to their team groups.\r\n\r\nYour generous donations will help me to help make our classroom a fun, inviting, learning environment from day one.\r\n\r\nIt costs lost of money out of my own pocket on resources to get our classroom ready. Please consider helping with this project to make our new school year a very successful one. Thank you!nannan
==================================================
My kindergarten students have varied disabilities ranging from speech and language delays, cognitive delays, gross/fine motor delays, to autism. They are eager beavers and always strive to work their hardest working past their limitations. \r\n\r\nThe materials we have are the ones I seek out for my students. I teach in a Title I school where most of the students receive free or reduced price lunch.  Despite their disabilities and limitations, my students love coming to school and come eager to learn and explore.Have you ever felt like you had ants in your pants and you needed to groove and move as you were in a meeting? This is how my kids feel all the time. The want to be able to move as they learn or so they say.Wobble chairs are the answer and I love then because they develop their core, which enhances gross motor and in Turn fine motor skills. \r\nThey also want to learn through games, my kids don't want to sit and do worksheets. They want to learn to count by jumping and playing. Physical engagement is the key to our success. The number toss and color and shape mats can make that happen. My students will forget they are doing work and just have the fun a 6 year old deserves.nannan
==================================================
In [11]:
# https://stackoverflow.com/a/47091490/4084039
import re

def decontracted(phrase):
    # specific
    phrase = re.sub(r"won't", "will not", phrase)
    phrase = re.sub(r"can\'t", "can not", phrase)

    # general
    phrase = re.sub(r"n\'t", " not", phrase)
    phrase = re.sub(r"\'re", " are", phrase)
    phrase = re.sub(r"\'s", " is", phrase)
    phrase = re.sub(r"\'d", " would", phrase)
    phrase = re.sub(r"\'ll", " will", phrase)
    phrase = re.sub(r"\'t", " not", phrase)
    phrase = re.sub(r"\'ve", " have", phrase)
    phrase = re.sub(r"\'m", " am", phrase)
    return phrase
In [12]:
sent = decontracted(project_data['essay'].values[20000])
print(sent)
print("="*50)
My kindergarten students have varied disabilities ranging from speech and language delays, cognitive delays, gross/fine motor delays, to autism. They are eager beavers and always strive to work their hardest working past their limitations. \r\n\r\nThe materials we have are the ones I seek out for my students. I teach in a Title I school where most of the students receive free or reduced price lunch.  Despite their disabilities and limitations, my students love coming to school and come eager to learn and explore.Have you ever felt like you had ants in your pants and you needed to groove and move as you were in a meeting? This is how my kids feel all the time. The want to be able to move as they learn or so they say.Wobble chairs are the answer and I love then because they develop their core, which enhances gross motor and in Turn fine motor skills. \r\nThey also want to learn through games, my kids do not want to sit and do worksheets. They want to learn to count by jumping and playing. Physical engagement is the key to our success. The number toss and color and shape mats can make that happen. My students will forget they are doing work and just have the fun a 6 year old deserves.nannan
==================================================
In [13]:
# \r \n \t remove from string python: http://texthandler.com/info/remove-line-breaks-python/
sent = sent.replace('\\r', ' ')
sent = sent.replace('\\"', ' ')
sent = sent.replace('\\n', ' ')
print(sent)
My kindergarten students have varied disabilities ranging from speech and language delays, cognitive delays, gross/fine motor delays, to autism. They are eager beavers and always strive to work their hardest working past their limitations.     The materials we have are the ones I seek out for my students. I teach in a Title I school where most of the students receive free or reduced price lunch.  Despite their disabilities and limitations, my students love coming to school and come eager to learn and explore.Have you ever felt like you had ants in your pants and you needed to groove and move as you were in a meeting? This is how my kids feel all the time. The want to be able to move as they learn or so they say.Wobble chairs are the answer and I love then because they develop their core, which enhances gross motor and in Turn fine motor skills.   They also want to learn through games, my kids do not want to sit and do worksheets. They want to learn to count by jumping and playing. Physical engagement is the key to our success. The number toss and color and shape mats can make that happen. My students will forget they are doing work and just have the fun a 6 year old deserves.nannan
In [14]:
#remove spacial character: https://stackoverflow.com/a/5843547/4084039
sent = re.sub('[^A-Za-z0-9]+', ' ', sent)
print(sent)
My kindergarten students have varied disabilities ranging from speech and language delays cognitive delays gross fine motor delays to autism They are eager beavers and always strive to work their hardest working past their limitations The materials we have are the ones I seek out for my students I teach in a Title I school where most of the students receive free or reduced price lunch Despite their disabilities and limitations my students love coming to school and come eager to learn and explore Have you ever felt like you had ants in your pants and you needed to groove and move as you were in a meeting This is how my kids feel all the time The want to be able to move as they learn or so they say Wobble chairs are the answer and I love then because they develop their core which enhances gross motor and in Turn fine motor skills They also want to learn through games my kids do not want to sit and do worksheets They want to learn to count by jumping and playing Physical engagement is the key to our success The number toss and color and shape mats can make that happen My students will forget they are doing work and just have the fun a 6 year old deserves nannan
In [15]:
# https://gist.github.com/sebleier/554280
# we are removing the words from the stop words list: 'no', 'nor', 'not'
stopwords= ['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're", "you've",\
            "you'll", "you'd", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', \
            'she', "she's", 'her', 'hers', 'herself', 'it', "it's", 'its', 'itself', 'they', 'them', 'their',\
            'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'this', 'that', "that'll", 'these', 'those', \
            'am', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', \
            'did', 'doing', 'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', \
            'at', 'by', 'for', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after',\
            'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further',\
            'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more',\
            'most', 'other', 'some', 'such', 'only', 'own', 'same', 'so', 'than', 'too', 'very', \
            's', 't', 'can', 'will', 'just', 'don', "don't", 'should', "should've", 'now', 'd', 'll', 'm', 'o', 're', \
            've', 'y', 'ain', 'aren', "aren't", 'couldn', "couldn't", 'didn', "didn't", 'doesn', "doesn't", 'hadn',\
            "hadn't", 'hasn', "hasn't", 'haven', "haven't", 'isn', "isn't", 'ma', 'mightn', "mightn't", 'mustn',\
            "mustn't", 'needn', "needn't", 'shan', "shan't", 'shouldn', "shouldn't", 'wasn', "wasn't", 'weren', "weren't", \
            'won', "won't", 'wouldn', "wouldn't"]
In [16]:
# Combining all the above stundents 
from tqdm import tqdm
preprocessed_essays = []
# tqdm is for printing the status bar
for sentance in tqdm(project_data['essay'].values):
    sent = decontracted(sentance)
    sent = sent.replace('\\r', ' ')
    sent = sent.replace('\\"', ' ')
    sent = sent.replace('\\n', ' ')
    sent = re.sub('[^A-Za-z0-9]+', ' ', sent)
    # https://gist.github.com/sebleier/554280
    sent = ' '.join(e for e in sent.split() if e not in stopwords)
    preprocessed_essays.append(sent.lower().strip())
project_data['preprocessed_essays'] = preprocessed_essays
100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 40000/40000 [00:39<00:00, 1017.30it/s]
In [17]:
# after preprocesing
preprocessed_essays[20000]
Out[17]:
'my kindergarten students varied disabilities ranging speech language delays cognitive delays gross fine motor delays autism they eager beavers always strive work hardest working past limitations the materials ones i seek students i teach title i school students receive free reduced price lunch despite disabilities limitations students love coming school come eager learn explore have ever felt like ants pants needed groove move meeting this kids feel time the want able move learn say wobble chairs answer i love develop core enhances gross motor turn fine motor skills they also want learn games kids not want sit worksheets they want learn count jumping playing physical engagement key success the number toss color shape mats make happen my students forget work fun 6 year old deserves nannan'

Number of words in combined Essay

In [18]:
proj_essay_wrd_count = []

for word in project_data['preprocessed_essays']:
    proj_essay_wrd_count.append(len(word.split()))
project_data['proj_essay_wrd_count'] = proj_essay_wrd_count

project_data.head(3)
Out[18]:
Unnamed: 0 id teacher_id teacher_prefix school_state project_submitted_datetime project_grade_category project_title project_essay_1 project_essay_2 project_essay_3 project_essay_4 project_resource_summary teacher_number_of_previously_posted_projects project_is_approved clean_categories clean_subcategories essay preprocessed_essays proj_essay_wrd_count
0 160221 p253737 c90749f5d961ff158d4b4d1e7dc665fc Mrs. IN 2016-12-05 13:43:57 Grades PreK-2 Educational Support for English Learners at Home My students are English learners that are work... \"The limits of your language are the limits o... NaN NaN My students need opportunities to practice beg... 0 0 Literacy_Language ESL Literacy My students are English learners that are work... my students english learners working english s... 161
1 140945 p258326 897464ce9ddc600bced1151f324dd63a Mr. FL 2016-10-25 09:22:10 Grades 6-8 Wanted: Projector for Hungry Learners Our students arrive to our school eager to lea... The projector we need for our school is very c... NaN NaN My students need a projector to help with view... 7 1 History_Civics Health_Sports Civics_Government TeamSports Our students arrive to our school eager to lea... our students arrive school eager learn they po... 109
2 21895 p182444 3465aaf82da834c0582ebd0ef8040ca0 Ms. AZ 2016-08-31 12:03:56 Grades 6-8 Soccer Equipment for AWESOME Middle School Stu... \r\n\"True champions aren't always the ones th... The students on the campus come to school know... NaN NaN My students need shine guards, athletic socks,... 1 0 Health_Sports Health_Wellness TeamSports \r\n\"True champions aren't always the ones th... true champions not always ones win guts by mia... 202

1.4 Preprocessing of `project_title`

In [19]:
# similarly you can preprocess the titles also
# printing some random essays.
print(project_data['project_title'].values[0])
print("="*50)
print(project_data['project_title'].values[150])
print("="*50)
print(project_data['project_title'].values[1000])
Educational Support for English Learners at Home
==================================================
More Movement with Hokki Stools
==================================================
Sailing Into a Super 4th Grade Year
In [20]:
# Combining all the above statemennts 
from tqdm import tqdm
preprocessed_titles = []
# tqdm is for printing the status bar
for sentance in tqdm(project_data['project_title'].values):
    sent = decontracted(sentance)
    sent = sent.replace('\\r', ' ')
    sent = sent.replace('\\"', ' ')
    sent = sent.replace('\\n', ' ')
    sent = re.sub('[^A-Za-z0-9]+', ' ', sent)
    # https://gist.github.com/sebleier/554280
    sent = ' '.join(e for e in sent.split() if e not in stopwords)
    preprocessed_titles.append(sent.lower().strip())
project_data['preprocessed_titles'] = preprocessed_titles
100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 40000/40000 [00:01<00:00, 23225.66it/s]
In [21]:
project_data.head(3)
Out[21]:
Unnamed: 0 id teacher_id teacher_prefix school_state project_submitted_datetime project_grade_category project_title project_essay_1 project_essay_2 ... project_essay_4 project_resource_summary teacher_number_of_previously_posted_projects project_is_approved clean_categories clean_subcategories essay preprocessed_essays proj_essay_wrd_count preprocessed_titles
0 160221 p253737 c90749f5d961ff158d4b4d1e7dc665fc Mrs. IN 2016-12-05 13:43:57 Grades PreK-2 Educational Support for English Learners at Home My students are English learners that are work... \"The limits of your language are the limits o... ... NaN My students need opportunities to practice beg... 0 0 Literacy_Language ESL Literacy My students are English learners that are work... my students english learners working english s... 161 educational support english learners home
1 140945 p258326 897464ce9ddc600bced1151f324dd63a Mr. FL 2016-10-25 09:22:10 Grades 6-8 Wanted: Projector for Hungry Learners Our students arrive to our school eager to lea... The projector we need for our school is very c... ... NaN My students need a projector to help with view... 7 1 History_Civics Health_Sports Civics_Government TeamSports Our students arrive to our school eager to lea... our students arrive school eager learn they po... 109 wanted projector hungry learners
2 21895 p182444 3465aaf82da834c0582ebd0ef8040ca0 Ms. AZ 2016-08-31 12:03:56 Grades 6-8 Soccer Equipment for AWESOME Middle School Stu... \r\n\"True champions aren't always the ones th... The students on the campus come to school know... ... NaN My students need shine guards, athletic socks,... 1 0 Health_Sports Health_Wellness TeamSports \r\n\"True champions aren't always the ones th... true champions not always ones win guts by mia... 202 soccer equipment awesome middle school students

3 rows × 21 columns

Number of words in project title

In [22]:
proj_title_wrd_count = []

for word in project_data['preprocessed_titles']:
    proj_title_wrd_count.append(len(word.split()))
project_data['proj_title_wrd_count'] = proj_title_wrd_count
project_data.head(3)
Out[22]:
Unnamed: 0 id teacher_id teacher_prefix school_state project_submitted_datetime project_grade_category project_title project_essay_1 project_essay_2 ... project_resource_summary teacher_number_of_previously_posted_projects project_is_approved clean_categories clean_subcategories essay preprocessed_essays proj_essay_wrd_count preprocessed_titles proj_title_wrd_count
0 160221 p253737 c90749f5d961ff158d4b4d1e7dc665fc Mrs. IN 2016-12-05 13:43:57 Grades PreK-2 Educational Support for English Learners at Home My students are English learners that are work... \"The limits of your language are the limits o... ... My students need opportunities to practice beg... 0 0 Literacy_Language ESL Literacy My students are English learners that are work... my students english learners working english s... 161 educational support english learners home 5
1 140945 p258326 897464ce9ddc600bced1151f324dd63a Mr. FL 2016-10-25 09:22:10 Grades 6-8 Wanted: Projector for Hungry Learners Our students arrive to our school eager to lea... The projector we need for our school is very c... ... My students need a projector to help with view... 7 1 History_Civics Health_Sports Civics_Government TeamSports Our students arrive to our school eager to lea... our students arrive school eager learn they po... 109 wanted projector hungry learners 4
2 21895 p182444 3465aaf82da834c0582ebd0ef8040ca0 Ms. AZ 2016-08-31 12:03:56 Grades 6-8 Soccer Equipment for AWESOME Middle School Stu... \r\n\"True champions aren't always the ones th... The students on the campus come to school know... ... My students need shine guards, athletic socks,... 1 0 Health_Sports Health_Wellness TeamSports \r\n\"True champions aren't always the ones th... true champions not always ones win guts by mia... 202 soccer equipment awesome middle school students 6

3 rows × 22 columns

In [23]:
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer

neg = []
pos = []
neu = []
compound = []

sid = SentimentIntensityAnalyzer()

for for_sentiment  in tqdm(project_data['preprocessed_essays']):

    neg.append(sid.polarity_scores(for_sentiment)['neg']) #Negative Sentiment score
    pos.append(sid.polarity_scores(for_sentiment)['pos']) #Positive Sentiment score
    neu.append(sid.polarity_scores(for_sentiment)['neu']) #Neutral Sentiment score
    compound.append(sid.polarity_scores(for_sentiment)['compound']) #Compound Sentiment score

# Creating new features    
project_data['Essay_neg_ss']      = neg
project_data['Essay_pos_ss']      = pos
project_data['Essay_neu_ss']      = neu
project_data['Essay_compound_ss'] = compound

project_data.head(3)
100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 40000/40000 [08:14<00:00, 80.93it/s]
Out[23]:
Unnamed: 0 id teacher_id teacher_prefix school_state project_submitted_datetime project_grade_category project_title project_essay_1 project_essay_2 ... clean_subcategories essay preprocessed_essays proj_essay_wrd_count preprocessed_titles proj_title_wrd_count Essay_neg_ss Essay_pos_ss Essay_neu_ss Essay_compound_ss
0 160221 p253737 c90749f5d961ff158d4b4d1e7dc665fc Mrs. IN 2016-12-05 13:43:57 Grades PreK-2 Educational Support for English Learners at Home My students are English learners that are work... \"The limits of your language are the limits o... ... ESL Literacy My students are English learners that are work... my students english learners working english s... 161 educational support english learners home 5 0.012 0.144 0.844 0.9694
1 140945 p258326 897464ce9ddc600bced1151f324dd63a Mr. FL 2016-10-25 09:22:10 Grades 6-8 Wanted: Projector for Hungry Learners Our students arrive to our school eager to lea... The projector we need for our school is very c... ... Civics_Government TeamSports Our students arrive to our school eager to lea... our students arrive school eager learn they po... 109 wanted projector hungry learners 4 0.048 0.283 0.669 0.9856
2 21895 p182444 3465aaf82da834c0582ebd0ef8040ca0 Ms. AZ 2016-08-31 12:03:56 Grades 6-8 Soccer Equipment for AWESOME Middle School Stu... \r\n\"True champions aren't always the ones th... The students on the campus come to school know... ... Health_Wellness TeamSports \r\n\"True champions aren't always the ones th... true champions not always ones win guts by mia... 202 soccer equipment awesome middle school students 6 0.122 0.219 0.659 0.9816

3 rows × 26 columns

1.4.1 Project_grade preprocessing

In [24]:
project_data['project_grade_category'] = project_data['project_grade_category'].str.replace(" ", "_")
project_data['project_grade_category'].value_counts()
Out[24]:
Grades_PreK-2    16255
Grades_3-5       13589
Grades_6-8        6170
Grades_9-12       3986
Name: project_grade_category, dtype: int64

Preprocessing teacher_prefix

In [25]:
project_data['teacher_prefix'] = project_data['teacher_prefix'].str.replace(".","")
project_data['teacher_prefix'].value_counts()
Out[25]:
Mrs        20907
Ms         14384
Mr          3851
Teacher      854
Dr             2
Name: teacher_prefix, dtype: int64

1.5 Preparing data for models

In [26]:
project_data.columns
Out[26]:
Index(['Unnamed: 0', 'id', 'teacher_id', 'teacher_prefix', 'school_state',
       'project_submitted_datetime', 'project_grade_category', 'project_title',
       'project_essay_1', 'project_essay_2', 'project_essay_3',
       'project_essay_4', 'project_resource_summary',
       'teacher_number_of_previously_posted_projects', 'project_is_approved',
       'clean_categories', 'clean_subcategories', 'essay',
       'preprocessed_essays', 'proj_essay_wrd_count', 'preprocessed_titles',
       'proj_title_wrd_count', 'Essay_neg_ss', 'Essay_pos_ss', 'Essay_neu_ss',
       'Essay_compound_ss'],
      dtype='object')

we are going to consider

   - school_state : categorical data
   - clean_categories : categorical data
   - clean_subcategories : categorical data
   - project_grade_category : categorical data
   - teacher_prefix : categorical data

   - project_title : text data
   - text : text data
   - project_resource_summary: text data (optinal)

   - quantity : numerical (optinal)
   - teacher_number_of_previously_posted_projects : numerical
   - price : numerical

Split data into train,test and Cross validate

In [27]:
Y = project_data['project_is_approved'].values
project_data.drop(['project_is_approved'], axis=1, inplace=True)
In [28]:
X = project_data
X.head(1)
Out[28]:
Unnamed: 0 id teacher_id teacher_prefix school_state project_submitted_datetime project_grade_category project_title project_essay_1 project_essay_2 ... clean_subcategories essay preprocessed_essays proj_essay_wrd_count preprocessed_titles proj_title_wrd_count Essay_neg_ss Essay_pos_ss Essay_neu_ss Essay_compound_ss
0 160221 p253737 c90749f5d961ff158d4b4d1e7dc665fc Mrs IN 2016-12-05 13:43:57 Grades_PreK-2 Educational Support for English Learners at Home My students are English learners that are work... \"The limits of your language are the limits o... ... ESL Literacy My students are English learners that are work... my students english learners working english s... 161 educational support english learners home 5 0.012 0.144 0.844 0.9694

1 rows × 25 columns

In [29]:
# train test split
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.33, stratify=Y)
X_train, X_cv, Y_train, Y_cv = train_test_split(X_train, Y_train, test_size=0.33, stratify=Y_train)

1.5.1 Vectorizing Categorical data

One Hot Encode - Clean_Categories

In [30]:
# we use count vectorizer to convert the values into one hot encoded features

print(X_train.shape, Y_train.shape)
print(X_test.shape, Y_test.shape)
print(X_cv.shape, Y_cv.shape)

print("="*100)

from sklearn.feature_extraction.text import CountVectorizer
vectorizer_categories = CountVectorizer(vocabulary=list(sorted_cat_dict.keys()), lowercase=False, binary=True)
vectorizer_categories.fit(X_train['clean_categories'].values)


categories_one_hot_train = vectorizer_categories.fit_transform(X_train['clean_categories'].values)
categories_one_hot_test = vectorizer_categories.transform(X_test['clean_categories'].values)
categories_one_hot_cv = vectorizer_categories.transform(X_cv['clean_categories'].values)

print("After vectorizations")

print("Shape of Train data - one hot encoding ",categories_one_hot_train.shape)
print("Shape of Test data - one hot encoding ",categories_one_hot_test.shape)
print("Shape of CV data - one hot encoding ",categories_one_hot_cv.shape)
print("="*100)
print(vectorizer_categories.get_feature_names())
print("="*100)
(17956, 25) (17956,)
(13200, 25) (13200,)
(8844, 25) (8844,)
====================================================================================================
After vectorizations
Shape of Train data - one hot encoding  (17956, 9)
Shape of Test data - one hot encoding  (13200, 9)
Shape of CV data - one hot encoding  (8844, 9)
====================================================================================================
['Warmth', 'Care_Hunger', 'History_Civics', 'Music_Arts', 'AppliedLearning', 'SpecialNeeds', 'Health_Sports', 'Math_Science', 'Literacy_Language']
====================================================================================================

One Hot Encode - Clean_Sub-Categories

In [31]:
# we use count vectorizer to convert the values into one 
print(X_train.shape, Y_train.shape)
print(X_test.shape, Y_test.shape)
print(X_cv.shape, Y_cv.shape)

print("="*100)


vectorizer_sub_cat = CountVectorizer(vocabulary=list(sorted_sub_cat_dict.keys()), lowercase=False, binary=True)
vectorizer_sub_cat.fit(X_train['clean_subcategories'].values)

sub_cat_one_hot_train = vectorizer_sub_cat.fit_transform(X_train['clean_subcategories'].values)
sub_cat_one_hot_test = vectorizer_sub_cat.transform(X_test['clean_subcategories'].values)
sub_cat_one_hot_cv = vectorizer_sub_cat.transform(X_cv['clean_subcategories'].values)

print("After vectorizations")

print("Shape of Train data - one hot encoding ",sub_cat_one_hot_train.shape)
print("Shape of Test data - one hot encoding",sub_cat_one_hot_test.shape)
print("Shape of CV data - one hot encoding",sub_cat_one_hot_cv.shape)
print("="*100)

print(vectorizer_sub_cat.get_feature_names())
print("="*100)
(17956, 25) (17956,)
(13200, 25) (13200,)
(8844, 25) (8844,)
====================================================================================================
After vectorizations
Shape of Train data - one hot encoding  (17956, 30)
Shape of Test data - one hot encoding (13200, 30)
Shape of CV data - one hot encoding (8844, 30)
====================================================================================================
['Economics', 'CommunityService', 'FinancialLiteracy', 'ParentInvolvement', 'Extracurricular', 'ForeignLanguages', 'Civics_Government', 'NutritionEducation', 'Warmth', 'Care_Hunger', 'SocialSciences', 'PerformingArts', 'CharacterEducation', 'TeamSports', 'Other', 'College_CareerPrep', 'Music', 'History_Geography', 'Health_LifeScience', 'EarlyDevelopment', 'ESL', 'Gym_Fitness', 'EnvironmentalScience', 'VisualArts', 'Health_Wellness', 'AppliedSciences', 'SpecialNeeds', 'Literature_Writing', 'Mathematics', 'Literacy']
====================================================================================================
In [32]:
# you can do the similar thing with state, teacher_prefix and project_grade_category also

One Hot Encode - School_States

In [33]:
my_counter = Counter()
for state in project_data['school_state'].values:
    my_counter.update(state.split())
In [34]:
school_state_cat_dict = dict(my_counter)
sorted_school_state_cat_dict = dict(sorted(school_state_cat_dict.items(), key=lambda kv: kv[1]))
In [35]:
## we use count vectorizer to convert the values into one hot encoded features

print(X_train.shape, Y_train.shape)
print(X_test.shape, Y_test.shape)
print(X_cv.shape, Y_cv.shape)

print("="*100)

vectorizer_school_state = CountVectorizer(vocabulary=list(sorted_school_state_cat_dict.keys()), lowercase=False, binary=True)
vectorizer_school_state.fit(X_train['school_state'].values)

school_state_one_hot_train = vectorizer_school_state.fit_transform(X_train['school_state'].values)
school_state_one_hot_test = vectorizer_school_state.transform(X_test['school_state'].values)
school_state_one_hot_cv = vectorizer_school_state.transform(X_cv['school_state'].values)

print("After vectorizations")


print("Shape of Train data - one hot encoding",school_state_one_hot_train.shape)
print("Shape of Test data - one hot encoding",school_state_one_hot_test.shape)
print("Shape of CV data - one hot encoding",school_state_one_hot_cv.shape)
print("="*100)
print(vectorizer_school_state.get_feature_names())
print("="*100)
(17956, 25) (17956,)
(13200, 25) (13200,)
(8844, 25) (8844,)
====================================================================================================
After vectorizations
Shape of Train data - one hot encoding (17956, 51)
Shape of Test data - one hot encoding (13200, 51)
Shape of CV data - one hot encoding (8844, 51)
====================================================================================================
['VT', 'WY', 'ND', 'MT', 'RI', 'NH', 'SD', 'AK', 'NE', 'DE', 'WV', 'HI', 'ME', 'NM', 'DC', 'KS', 'ID', 'IA', 'AR', 'CO', 'MN', 'MS', 'OR', 'KY', 'MD', 'NV', 'AL', 'CT', 'UT', 'TN', 'WI', 'VA', 'NJ', 'AZ', 'OK', 'MA', 'LA', 'WA', 'MO', 'IN', 'OH', 'PA', 'MI', 'SC', 'GA', 'IL', 'NC', 'FL', 'TX', 'NY', 'CA']
====================================================================================================

One Hot Encode - Project_Grade_Category

In [36]:
my_counter = Counter()
for project_grade in project_data['project_grade_category'].values:
    my_counter.update(project_grade.split())
In [37]:
project_grade_cat_dict = dict(my_counter)
sorted_project_grade_cat_dict = dict(sorted(project_grade_cat_dict.items(), key=lambda kv: kv[1]))
In [38]:
## we use count vectorizer to convert the values into one hot encoded features

print(X_train.shape, Y_train.shape)
print(X_test.shape, Y_test.shape)
print(X_cv.shape, Y_cv.shape)

print("="*100)

vectorizer_project_grade_cat = CountVectorizer(vocabulary=list(sorted_project_grade_cat_dict.keys()), lowercase=False, binary=True)
vectorizer_project_grade_cat.fit(X_train['project_grade_category'].values)

project_grade_cat_one_hot_train = vectorizer_project_grade_cat.fit_transform(X_train['project_grade_category'].values)
project_grade_cat_one_hot_test = vectorizer_project_grade_cat.transform(X_test['project_grade_category'].values)
project_grade_cat_one_hot_cv = vectorizer_project_grade_cat.transform(X_cv['project_grade_category'].values)

print("After vectorizations")
print("="*100)
print("Shape of Train data - one hot encoding",project_grade_cat_one_hot_train.shape)
print("Shape of Test data - one hot encoding",project_grade_cat_one_hot_test.shape)
print("Shape of CV data - one hot encoding",project_grade_cat_one_hot_cv.shape)
print("="*100)
print(vectorizer_project_grade_cat.get_feature_names())
(17956, 25) (17956,)
(13200, 25) (13200,)
(8844, 25) (8844,)
====================================================================================================
After vectorizations
====================================================================================================
Shape of Train data - one hot encoding (17956, 4)
Shape of Test data - one hot encoding (13200, 4)
Shape of CV data - one hot encoding (8844, 4)
====================================================================================================
['Grades_9-12', 'Grades_6-8', 'Grades_3-5', 'Grades_PreK-2']

One Hot Encode - Teacher_Prefix

In [39]:
my_counter = Counter()
for teacher_prefix in project_data['teacher_prefix'].values:
    teacher_prefix = str(teacher_prefix)
    my_counter.update(teacher_prefix.split())
In [40]:
teacher_prefix_cat_dict = dict(my_counter)
sorted_teacher_prefix_cat_dict = dict(sorted(teacher_prefix_cat_dict.items(), key=lambda kv: kv[1]))
In [41]:
vectorizer_teacher_prefix_cat = CountVectorizer(vocabulary=list(sorted_teacher_prefix_cat_dict.keys()), lowercase=False, binary=True)
vectorizer_teacher_prefix_cat.fit(X_train['teacher_prefix'].values.astype("U"))

print(X_train.shape, Y_train.shape)
print(X_test.shape, Y_test.shape)
print(X_cv.shape, Y_cv.shape)

print("="*100)

teacher_prefix_cat_one_hot_train = vectorizer_teacher_prefix_cat.fit_transform(X_train['teacher_prefix'].values.astype("U"))
teacher_prefix_cat_one_hot_test = vectorizer_teacher_prefix_cat.transform(X_test['teacher_prefix'].values.astype("U"))
teacher_prefix_cat_one_hot_cv = vectorizer_teacher_prefix_cat.transform(X_cv['teacher_prefix'].values.astype("U"))
print("After vectorizations")
print("="*100)

print("Shape of Train data - one hot encoding",teacher_prefix_cat_one_hot_train.shape)
print("Shape of Test data - one hot encoding ",teacher_prefix_cat_one_hot_test.shape)
print("Shape of CV data - one hot encoding ",teacher_prefix_cat_one_hot_cv.shape)
print("="*100)


print(vectorizer_teacher_prefix_cat.get_feature_names())
(17956, 25) (17956,)
(13200, 25) (13200,)
(8844, 25) (8844,)
====================================================================================================
After vectorizations
====================================================================================================
Shape of Train data - one hot encoding (17956, 6)
Shape of Test data - one hot encoding  (13200, 6)
Shape of CV data - one hot encoding  (8844, 6)
====================================================================================================
['nan', 'Dr', 'Teacher', 'Mr', 'Ms', 'Mrs']

1.5.2 Vectorizing Text data

1.5.2.1 Bag of words

BOW of eassys - Train/Test/CV Data

In [42]:
# We are considering only the words which appeared in at least 10 documents(rows or projects).
vectorizer_essay_bow = CountVectorizer(ngram_range=(2, 2),min_df=10,max_features=5000)
vectorizer_essay_bow.fit(X_train['preprocessed_essays'])

# BOW for essays Train Data
essay_bow_train = vectorizer_essay_bow.fit_transform(X_train['preprocessed_essays'])
print("Shape of matrix for TRAIN data ",essay_bow_train.shape)

# BOW for essays Test Data
essay_bow_test = vectorizer_essay_bow.transform(X_test['preprocessed_essays'])
print("Shape of matrix for TEST data",essay_bow_test.shape)

# BOW for essays CV Data
essay_bow_cv = vectorizer_essay_bow.transform(X_cv['preprocessed_essays'])
print("Shape of matrix for CV data ",essay_bow_cv.shape)
Shape of matrix for TRAIN data  (17956, 5000)
Shape of matrix for TEST data (13200, 5000)
Shape of matrix for CV data  (8844, 5000)

BOW of Project Titles - Train/Test/CV Data

In [43]:
vectorizer_title_bow = CountVectorizer(ngram_range=(2, 2),min_df=10,max_features=5000)
vectorizer_title_bow.fit(X_train['preprocessed_titles'])

# BOW for title Train Data
title_bow_train = vectorizer_title_bow.fit_transform(X_train['preprocessed_titles'])
print("Shape of matrix for TRAIN data ",title_bow_train.shape)

# BOW for title Test Data
title_bow_test = vectorizer_title_bow.transform(X_test['preprocessed_titles'])
print("Shape of matrix for TEST data",title_bow_test.shape)

# BOW for title CV Data
title_bow_cv = vectorizer_title_bow.transform(X_cv['preprocessed_titles'])
print("Shape of matrix for CV data ",title_bow_cv.shape)
Shape of matrix for TRAIN data  (17956, 491)
Shape of matrix for TEST data (13200, 491)
Shape of matrix for CV data  (8844, 491)

1.5.2.2 TFIDF vectorizer for essay

In [44]:
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer_essay_tfidf = TfidfVectorizer(ngram_range=(2, 2),min_df=10,max_features=5000)
vectorizer_essay_tfidf.fit(X_train['preprocessed_essays'])

#tidf Train Data
essay_tfidf_train = vectorizer_essay_tfidf.fit_transform(X_train['preprocessed_essays'])
print("Shape of matrix for TRAIN data",essay_tfidf_train.shape)

#tidf Test Data
essay_tfidf_test = vectorizer_essay_tfidf.transform(X_test['preprocessed_essays'])
print("Shape of matrix for TEST data",essay_tfidf_test.shape)

#tidf CV Data
essay_tfidf_cv = vectorizer_essay_tfidf.transform(X_cv['preprocessed_essays'])
print("Shape of matrix for CV data",essay_tfidf_cv.shape)
Shape of matrix for TRAIN data (17956, 5000)
Shape of matrix for TEST data (13200, 5000)
Shape of matrix for CV data (8844, 5000)

TFIDF vectorizer for Title

In [45]:
vectorizer_title_tfidf = TfidfVectorizer(ngram_range=(2, 2),min_df=10,max_features=5000)
vectorizer_title_tfidf.fit(X_train['preprocessed_titles'])

#tidf Train Data
title_tfidf_train = vectorizer_title_tfidf.fit_transform(X_train['preprocessed_titles'])
print("Shape of matrix for TRAIN data",title_tfidf_train.shape)

#tidf Test Data
title_tfidf_test = vectorizer_title_tfidf.transform(X_test['preprocessed_titles'])
print("Shape of matrix for TEST data",title_tfidf_test.shape)

#tidf CV Data
title_tfidf_cv = vectorizer_title_tfidf.transform(X_cv['preprocessed_titles'])
print("Shape of matrix for CV data",title_tfidf_cv.shape)
Shape of matrix for TRAIN data (17956, 491)
Shape of matrix for TEST data (13200, 491)
Shape of matrix for CV data (8844, 491)

1.5.2.3 Using Pretrained Models: Avg W2V

In [46]:
# stronging variables into pickle files python: http://www.jessicayung.com/how-to-use-pickle-to-save-and-load-variables-in-python/
# make sure you have the glove_vectors file
with open('glove_vectors', 'rb') as f:
    model = pickle.load(f)
    glove_words =  set(model.keys())
In [47]:
# average Word2Vec Function
# compute average word2vec for each review.
# the avg-w2v for each sentence/review is stored in this list
def avg_w2v_vectors_func(sentance):
    vector = np.zeros(300) # as word vectors are of zero length
    cnt_words =0; # num of words with a valid vector in the sentence/review
    for word in sentence.split(): # for each word in a review/sentence
        if word in glove_words:
            vector += model[word]
            cnt_words += 1
    if cnt_words != 0:
        vector /= cnt_words
    return vector

Train/Test/CV Data - Avg-W2V for essay

In [48]:
essay_avg_w2v_train = []
essay_avg_w2v_test  = []
essay_avg_w2v_cv    = []

for sentence in tqdm(X_train['preprocessed_essays']):
    essay_avg_w2v_train.append(avg_w2v_vectors_func(sentance)) # Avg-w2v for Train data
    
# Avg-w2v for Train data    
print("len(essay_avg_w2v_train):",len(essay_avg_w2v_train))
print("len(essay_avg_w2v_train[0])",len(essay_avg_w2v_train[0]))

for sentence in tqdm(X_test['preprocessed_essays']):
    essay_avg_w2v_test.append(avg_w2v_vectors_func(sentance)) # Avg-w2v for Test data

# Avg-w2v for Test data
print("len(essay_avg_w2v_test):",len(essay_avg_w2v_test))
print("len(essay_avg_w2v_test[0])",len(essay_avg_w2v_test[0]))


for sentence in tqdm(X_cv['preprocessed_essays']):    
    essay_avg_w2v_cv.append(avg_w2v_vectors_func(sentance)) # Avg-w2v for CV data

# Avg-w2v for CV data
print("len(essay_avg_w2v_cv):",len(essay_avg_w2v_cv))
print("len(essay_avg_w2v_cv[0])",len(essay_avg_w2v_cv[0]))
100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 17956/17956 [00:10<00:00, 1764.19it/s]
len(essay_avg_w2v_train): 17956
len(essay_avg_w2v_train[0]) 300
100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 13200/13200 [00:07<00:00, 1852.28it/s]
len(essay_avg_w2v_test): 13200
len(essay_avg_w2v_test[0]) 300
100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 8844/8844 [00:05<00:00, 1745.03it/s]
len(essay_avg_w2v_cv): 8844
len(essay_avg_w2v_cv[0]) 300
In [49]:
title_avg_w2v_train = []
title_avg_w2v_test  = []

for sentence in tqdm(X_train['preprocessed_titles']):
    title_avg_w2v_train.append(avg_w2v_vectors_func(sentance)) # Avg-w2v for Train data
    
# Avg-w2v for Train data    
print("len(title_avg_w2v_train):",len(title_avg_w2v_train))
print("len(title_avg_w2v_train[0])",len(title_avg_w2v_train[0]))

for sentence in tqdm(X_test['preprocessed_titles']):
    title_avg_w2v_test.append(avg_w2v_vectors_func(sentance)) # Avg-w2v for Test data

# Avg-w2v for Test data
print("len(title_avg_w2v_test):",len(title_avg_w2v_test))
print("len(title_avg_w2v_test[0])",len(title_avg_w2v_test[0]))
100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 17956/17956 [00:00<00:00, 31029.90it/s]
len(title_avg_w2v_train): 17956
len(title_avg_w2v_train[0]) 300
100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 13200/13200 [00:00<00:00, 33521.76it/s]
len(title_avg_w2v_test): 13200
len(title_avg_w2v_test[0]) 300

1.5.2.3 Using Pretrained Models: TFIDF weighted W2V

In [50]:
# S = ["abc def pqr", "def def def abc", "pqr pqr def"]
tfidf_model = TfidfVectorizer()
tfidf_model.fit(X_train['preprocessed_essays'])
# we are converting a dictionary with word as a key, and the idf as a value
dictionary = dict(zip(tfidf_model.get_feature_names(), list(tfidf_model.idf_)))
tfidf_words = set(tfidf_model.get_feature_names())
In [51]:
# Compute  TFIDF weighted W2V for each sentence of the review.

def tf_idf_weight_func(sentence): # for each review/sentence
    vector = np.zeros(300) # as word vectors are of zero length
    tf_idf_weight =0; # num of words with a valid vector in the sentence/review
    for word in sentence.split(): # for each word in a review/sentence
        if (word in glove_words) and (word in tfidf_words):
            vec = model[word] # getting the vector for each word
            # here we are multiplying idf value(dictionary[word]) and the tf value((sentence.count(word)/len(sentence.split())))
            tf_idf = dictionary[word]*(sentence.count(word)/len(sentence.split())) # getting the tfidf value for each word
            vector += (vec * tf_idf) # calculating tfidf weighted w2v
            tf_idf_weight += tf_idf
    if tf_idf_weight != 0:
        vector /= tf_idf_weight
    return vector

Train/Test/CV Data - TFIDF weighted W2V for essay

In [52]:
essay_tfidf_w2v_train = []
essay_tfidf_w2v_test  = []
essay_tfidf_w2v_cv    = []

for sentence in tqdm(X_train['preprocessed_essays']):
    essay_tfidf_w2v_train.append(tf_idf_weight_func(sentance)) #  TFIDF weighted W2V for Train data
print("len(essay_tfidf_w2v_train)",len(essay_tfidf_w2v_train))
print("len(essay_tfidf_w2v_train[0])",len(essay_tfidf_w2v_train[0]))

for sentence in tqdm(X_test['preprocessed_essays']):
    essay_tfidf_w2v_test.append(tf_idf_weight_func(sentance)) #  TFIDF weighted W2V for Test data
print("len(essay_tfidf_w2v_test)",len(essay_tfidf_w2v_test))
print("len(essay_tfidf_w2v_test[0])",len(essay_tfidf_w2v_test[0]))

for sentence in tqdm(X_cv['preprocessed_essays']):
    essay_tfidf_w2v_cv.append(tf_idf_weight_func(sentance)) #  TFIDF weighted W2V for CV data
print("len(essay_tfidf_w2v_cv)",len(essay_tfidf_w2v_cv))
print("len(essay_tfidf_w2v_cv[0])",len(essay_tfidf_w2v_cv[0]))
100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 17956/17956 [00:00<00:00, 29794.71it/s]
len(essay_tfidf_w2v_train) 17956
len(essay_tfidf_w2v_train[0]) 300
100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 13200/13200 [00:00<00:00, 27009.35it/s]
len(essay_tfidf_w2v_test) 13200
len(essay_tfidf_w2v_test[0]) 300
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 8844/8844 [00:00<00:00, 23660.61it/s]
len(essay_tfidf_w2v_cv) 8844
len(essay_tfidf_w2v_cv[0]) 300

Train/Test/CV Data - Avg-W2V for essay

In [53]:
title_avg_w2v_train = []
title_avg_w2v_test  = []
title_avg_w2v_cv    = []

for sentence in tqdm(X_train['preprocessed_titles']):
    title_avg_w2v_train.append(avg_w2v_vectors_func(sentance)) # Avg-w2v for Train data
    
# Avg-w2v for Train data    
print("len(title_avg_w2v_train):",len(title_avg_w2v_train))
print("len(title_avg_w2v_train[0])",len(title_avg_w2v_train[0]))

for sentence in tqdm(X_test['preprocessed_titles']):
    title_avg_w2v_test.append(avg_w2v_vectors_func(sentance)) # Avg-w2v for Test data

# Avg-w2v for Test data
print("len(title_avg_w2v_test):",len(title_avg_w2v_test))
print("len(title_avg_w2v_test[0])",len(title_avg_w2v_test[0]))


for sentence in tqdm(X_cv['preprocessed_titles']):    
    title_avg_w2v_cv.append(avg_w2v_vectors_func(sentance)) # Avg-w2v for CV data

# Avg-w2v for CV data
print("len(title_avg_w2v_cv):",len(title_avg_w2v_cv))
print("len(title_avg_w2v_cv[0])",len(title_avg_w2v_cv[0]))
100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 17956/17956 [00:00<00:00, 33269.60it/s]
len(title_avg_w2v_train): 17956
len(title_avg_w2v_train[0]) 300
100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 13200/13200 [00:00<00:00, 33952.58it/s]
len(title_avg_w2v_test): 13200
len(title_avg_w2v_test[0]) 300
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 8844/8844 [00:00<00:00, 29794.53it/s]
len(title_avg_w2v_cv): 8844
len(title_avg_w2v_cv[0]) 300

Train/Test/CV Data - TFIDF weighted W2V for Project Titles

In [54]:
title_tfidf_w2v_train  = []
title_tfidf_w2v_test  = []
title_tfidf_w2v_cv    = []

for sentence in tqdm(X_train['preprocessed_titles']):
    title_tfidf_w2v_train.append(tf_idf_weight_func(sentance)) #  TFIDF weighted W2V for Train data
print("len(title_tfidf_w2v_train)",len(title_tfidf_w2v_train))
print("len(title_tfidf_w2v_train[0])",len(title_tfidf_w2v_train[0]))

for sentence in tqdm(X_test['preprocessed_titles']):
    title_tfidf_w2v_test.append(tf_idf_weight_func(sentance)) #  TFIDF weighted W2V for Test data
print("len(title_tfidf_w2v_test)",len(title_tfidf_w2v_test))
print("len(title_tfidf_w2v_test[0])",len(title_tfidf_w2v_test[0]))

for sentence in tqdm(X_cv['preprocessed_titles']):
    title_tfidf_w2v_cv.append(tf_idf_weight_func(sentance)) #  TFIDF weighted W2V for CV data
print("len(title_tfidf_w2v_cv)",len(title_tfidf_w2v_cv))
print("len(title_tfidf_w2v_cv[0])",len(title_tfidf_w2v_cv[0]))
100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 17956/17956 [00:00<00:00, 27811.60it/s]
len(title_tfidf_w2v_train) 17956
len(title_tfidf_w2v_train[0]) 300
100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 13200/13200 [00:00<00:00, 28105.89it/s]
len(title_tfidf_w2v_test) 13200
len(title_tfidf_w2v_test[0]) 300
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 8844/8844 [00:00<00:00, 23106.77it/s]
len(title_tfidf_w2v_cv) 8844
len(title_tfidf_w2v_cv[0]) 300

1.5.3 Vectorizing Numerical features

In [55]:
price_data = resource_data.groupby('id').agg({'price':'sum', 'quantity':'sum'}).reset_index()
X_train = pd.merge(X_train, price_data, on='id', how='left')
X_test = pd.merge(X_test, price_data, on='id', how='left')
X_cv = pd.merge(X_cv, price_data, on='id', how='left')
In [56]:
from sklearn.preprocessing import Normalizer

print(X_train.shape, Y_train.shape)
print(X_test.shape, Y_test.shape)
print(X_cv.shape, Y_cv.shape)

print("="*100)
normalizer = Normalizer()

# normalizer.fit(X_train['price'].values)
# this will rise an error Expected 2D array, got 1D array instead: 
# array=[105.22 215.96  96.01 ... 368.98  80.53 709.67].
# Reshape your data either using 
# array.reshape(-1, 1) if your data has a single feature 
# array.reshape(1, -1)  if it contains a single sample.

normalizer.fit(X_train['price'].values.reshape(-1,1))

price_data_train = normalizer.fit_transform(X_train['price'].values.reshape(-1,1))

price_data_test = normalizer.transform(X_test['price'].values.reshape(-1,1))

price_data_cv = normalizer.transform(X_cv['price'].values.reshape(-1,1))

print("After vectorizations")
print("="*100)
print(price_data_train.shape, Y_train.shape)
print(price_data_test.shape, Y_test.shape)
print(price_data_cv.shape, Y_cv.shape)
print("="*100)
(17956, 27) (17956,)
(13200, 27) (13200,)
(8844, 27) (8844,)
====================================================================================================
After vectorizations
====================================================================================================
(17956, 1) (17956,)
(13200, 1) (13200,)
(8844, 1) (8844,)
====================================================================================================

Vectorizing - Quantity Feature

In [57]:
normalizer = Normalizer()

# normalizer.fit(X_train['price'].values)
# this will rise an error Expected 2D array, got 1D array instead: 
# array=[105.22 215.96  96.01 ... 368.98  80.53 709.67].
# Reshape your data either using 
# array.reshape(-1, 1) if your data has a single feature 
# array.reshape(1, -1)  if it contains a single sample.

print(X_train.shape, Y_train.shape)
print(X_test.shape, Y_test.shape)
print(X_cv.shape, Y_cv.shape)

print("="*100)
normalizer.fit(X_train['quantity'].values.reshape(-1,1))

quant_train = normalizer.fit_transform(X_train['quantity'].values.reshape(-1,1))
quant_cv = normalizer.transform(X_cv['quantity'].values.reshape(-1,1))
quant_test = normalizer.transform(X_test['quantity'].values.reshape(-1,1))

print("="*100)
print("After vectorizations")
print(quant_train.shape, Y_train.shape)
print(quant_cv.shape, Y_cv.shape)
print(quant_test.shape, Y_test.shape)
print("="*100)
(17956, 27) (17956,)
(13200, 27) (13200,)
(8844, 27) (8844,)
====================================================================================================
====================================================================================================
After vectorizations
(17956, 1) (17956,)
(8844, 1) (8844,)
(13200, 1) (13200,)
====================================================================================================

Vectorizing - teacher_number_of_previously_posted_projects

In [58]:
normalizer = Normalizer()

# normalizer.fit(X_train['price'].values)
# this will rise an error Expected 2D array, got 1D array instead: 
# array=[105.22 215.96  96.01 ... 368.98  80.53 709.67].
# Reshape your data either using 
# array.reshape(-1, 1) if your data has a single feature 
# array.reshape(1, -1)  if it contains a single sample.

print(X_train.shape, Y_train.shape)
print(X_test.shape, Y_test.shape)
print(X_cv.shape, Y_cv.shape)

print("="*100)
normalizer.fit(X_train['teacher_number_of_previously_posted_projects'].values.reshape(-1,1))

prev_no_projects_train = normalizer.fit_transform(X_train['teacher_number_of_previously_posted_projects'].values.reshape(-1,1))
prev_no_projects_cv = normalizer.transform(X_cv['teacher_number_of_previously_posted_projects'].values.reshape(-1,1))
prev_no_projects_test = normalizer.transform(X_test['teacher_number_of_previously_posted_projects'].values.reshape(-1,1))

print("="*100)
print("After vectorizations")
print(prev_no_projects_train.shape, Y_train.shape)
print(prev_no_projects_cv.shape, Y_cv.shape)
print(prev_no_projects_test.shape, Y_test.shape)
print("="*100)
(17956, 27) (17956,)
(13200, 27) (13200,)
(8844, 27) (8844,)
====================================================================================================
====================================================================================================
After vectorizations
(17956, 1) (17956,)
(8844, 1) (8844,)
(13200, 1) (13200,)
====================================================================================================

Vectorizing - Word count title

In [59]:
normalizer = Normalizer()

normalizer.fit(X_train['proj_title_wrd_count'].values.reshape(-1,1))

title_cnt_train = normalizer.fit_transform(X_train['proj_title_wrd_count'].values.reshape(-1,1))
title_cnt_test = normalizer.transform(X_test['proj_title_wrd_count'].values.reshape(-1,1))

print("="*100)
print("After vectorizations")
print(title_cnt_train.shape, Y_train.shape)
print(title_cnt_test.shape, Y_test.shape)
print("="*100)
====================================================================================================
After vectorizations
(17956, 1) (17956,)
(13200, 1) (13200,)
====================================================================================================

Vectorizing - Essay count title

In [60]:
normalizer = Normalizer()

normalizer.fit(X_train['proj_essay_wrd_count'].values.reshape(-1,1))

essay_cnt_train = normalizer.fit_transform(X_train['proj_essay_wrd_count'].values.reshape(-1,1))
essay_cnt_test = normalizer.transform(X_test['proj_essay_wrd_count'].values.reshape(-1,1))

print("="*100)
print("After vectorizations")
print(title_cnt_train.shape, Y_train.shape)
print(title_cnt_test.shape, Y_test.shape)
print("="*100)
====================================================================================================
After vectorizations
(17956, 1) (17956,)
(13200, 1) (13200,)
====================================================================================================

Vectorizing - Sentiment Score negative

In [61]:
normalizer = Normalizer()

normalizer.fit(X_train['Essay_neg_ss'].values.reshape(-1,1))

essay_neg_train = normalizer.fit_transform(X_train['Essay_neg_ss'].values.reshape(-1,1))
essay_neg_test = normalizer.transform(X_test['Essay_neg_ss'].values.reshape(-1,1))

print("="*100)
print("After vectorizations")
print(essay_neg_train.shape, Y_train.shape)
print(essay_neg_test.shape, Y_test.shape)
print("="*100)
====================================================================================================
After vectorizations
(17956, 1) (17956,)
(13200, 1) (13200,)
====================================================================================================

Vectorizing - Sentiment Score positive

In [62]:
normalizer = Normalizer()

normalizer.fit(X_train['Essay_pos_ss'].values.reshape(-1,1))

essay_pos_train = normalizer.fit_transform(X_train['Essay_pos_ss'].values.reshape(-1,1))
essay_pos_test = normalizer.transform(X_test['Essay_pos_ss'].values.reshape(-1,1))

print("="*100)
print("After vectorizations")
print(essay_pos_train.shape, Y_train.shape)
print(essay_pos_test.shape, Y_test.shape)
print("="*100)
====================================================================================================
After vectorizations
(17956, 1) (17956,)
(13200, 1) (13200,)
====================================================================================================

Vectorizing - Sentiment Score neutral

In [63]:
normalizer = Normalizer()

normalizer.fit(X_train['Essay_neu_ss'].values.reshape(-1,1))

essay_neu_train = normalizer.fit_transform(X_train['Essay_neu_ss'].values.reshape(-1,1))
essay_neu_test = normalizer.transform(X_test['Essay_neu_ss'].values.reshape(-1,1))

print("="*100)
print("After vectorizations")
print(essay_neu_train.shape, Y_train.shape)
print(essay_neu_test.shape, Y_test.shape)
print("="*100)
====================================================================================================
After vectorizations
(17956, 1) (17956,)
(13200, 1) (13200,)
====================================================================================================

Vectorizing - Sentiment Score compound

In [64]:
normalizer = Normalizer()

normalizer.fit(X_train['Essay_compound_ss'].values.reshape(-1,1))

essay_compound_train = normalizer.fit_transform(X_train['Essay_compound_ss'].values.reshape(-1,1))
essay_compund_test = normalizer.transform(X_test['Essay_compound_ss'].values.reshape(-1,1))

print("="*100)
print("After vectorizations")
print(essay_compound_train.shape, Y_train.shape)
print(essay_compund_test.shape, Y_test.shape)
print("="*100)
====================================================================================================
After vectorizations
(17956, 1) (17956,)
(13200, 1) (13200,)
====================================================================================================

Assignment 8: DT

  1. Apply Decision Tree Classifier(DecisionTreeClassifier) on these feature sets
    • Set 1: categorical, numerical features + project_title(BOW) + preprocessed_eassay (BOW)
    • Set 2: categorical, numerical features + project_title(TFIDF)+ preprocessed_eassay (TFIDF)
    • Set 3: categorical, numerical features + project_title(AVG W2V)+ preprocessed_eassay (AVG W2V)
    • Set 4: categorical, numerical features + project_title(TFIDF W2V)+ preprocessed_eassay (TFIDF W2V)

  2. Hyper paramter tuning (best `depth` in range [1, 5, 10, 50, 100, 500, 100], and the best `min_samples_split` in range [5, 10, 100, 500])
    • Find the best hyper parameter which will give the maximum AUC value
    • Find the best hyper paramter using k-fold cross validation or simple cross validation data
    • Use gridsearch cv or randomsearch cv or you can also write your own for loops to do this task of hyperparameter tuning

  3. Graphviz
    • Visualize your decision tree with Graphviz. It helps you to understand how a decision is being made, given a new vector.
    • Since feature names are not obtained from word2vec related models, visualize only BOW & TFIDF decision trees using Graphviz
    • Make sure to print the words in each node of the decision tree instead of printing its index.
    • Just for visualization purpose, limit max_depth to 2 or 3 and either embed the generated images of graphviz in your notebook, or directly upload them as .png files.

  4. Representation of results
    • You need to plot the performance of model both on train data and cross validation data for each hyper parameter, like shown in the figure
    • Once after you found the best hyper parameter, you need to train your model with it, and find the AUC on test data and plot the ROC curve on both train and test.
    • Along with plotting ROC curve, you need to print the confusion matrix with predicted and original labels of test data points
    • Once after you plot the confusion matrix with the test data, get all the `false positive data points`
      • Plot the WordCloud WordCloud
      • Plot the box plot with the `price` of these `false positive data points`
      • Plot the pdf with the `teacher_number_of_previously_posted_projects` of these `false positive data points`

  5. [Task-2]
    • Select 5k best features from features of Set 2 using`feature_importances_`, discard all the other remaining features and then apply any of the model of you choice i.e. (Dession tree, Logistic Regression, Linear SVM), you need to do hyperparameter tuning corresponding to the model you selected and procedure in step 2 and step 3

  6. Conclusion
    • You need to summarize the results at the end of the notebook, summarize it in the table format. To print out a table please refer to this prettytable library link

2. Decision Tree

SET 1

Applying Decision trees on BOW

In [65]:
from scipy.sparse import hstack

X_train_merge = hstack((categories_one_hot_train, sub_cat_one_hot_train, school_state_one_hot_train, project_grade_cat_one_hot_train, teacher_prefix_cat_one_hot_train, price_data_train, quant_train, prev_no_projects_train,title_bow_train, essay_bow_train)).tocsr()
X_test_merge = hstack((categories_one_hot_test, sub_cat_one_hot_test, school_state_one_hot_test, project_grade_cat_one_hot_test, teacher_prefix_cat_one_hot_test, price_data_test, quant_test, prev_no_projects_test,title_bow_test, essay_bow_test)).tocsr()

print("Final Data matrix")
print("="*100)
print(X_train_merge.shape, Y_train.shape)

print(X_test_merge.shape, Y_test.shape)
print("="*100)
Final Data matrix
====================================================================================================
(17956, 5594) (17956,)
(13200, 5594) (13200,)
====================================================================================================

Best hyper parameter using the ROC/AUC higest value and K-fold cross validation.

In [66]:
def batch_predict(clf, data):
    # roc_auc_score(y_true, y_score) the 2nd parameter should be probability estimates of the positive class
    # not the predicted outputs

    y_data_pred = []
    tr_loop = data.shape[0] - data.shape[0]%1000
    # consider you X_tr shape is 49041, then your cr_loop will be 49041 - 49041%1000 = 49000
    # in this for loop we will iterate unti the last 1000 multiplier
    for i in range(0, tr_loop, 1000):
        y_data_pred.extend(clf.predict_proba(data[i:i+1000])[:,1])
    # we will be predicting for the last data points
    y_data_pred.extend(clf.predict_proba(data[tr_loop:])[:,1])
    
    return y_data_pred
In [ ]:
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier

dt = DecisionTreeClassifier()

parameters = {'max_depth':[1, 5, 10, 50, 100, 500], 'min_samples_split': [5, 10, 100, 500]}


clf = GridSearchCV(dt, parameters, cv= 10, scoring='roc_auc')

clf.fit(X_train_merge,Y_train)

train_auc= clf.cv_results_['mean_train_score']
train_auc_std= clf.cv_results_['std_train_score']
cv_auc = clf.cv_results_['mean_test_score'] 
cv_auc_std= clf.cv_results_['std_test_score']
parm_max_depth = clf.cv_results_['param_max_depth']
param_min_samples_split = clf.cv_results_['param_min_samples_split']

Heatmap for the hyperparameters

In [68]:
#https://towardsdatascience.com/using-3d-visualizations-to-tune-hyperparameters-of-ml-models-with-python-ba2885eab2e9

df_gridsearch = pd.DataFrame(clf.cv_results_)

#Maximum AUC score on train set VS max_depth, min_samples_split
max_scores = df_gridsearch.groupby(['param_max_depth',
                                    'param_min_samples_split']).max().unstack()[['mean_test_score', 'mean_train_score']]
plt.rcParams["figure.figsize"] = (10, 7)

title = 'Maximum AUC score on train set VS max_depth, min_samples_split'

sns.heatmap(max_scores.mean_train_score, annot=True, fmt='.4g');
plt.title(title);
In [69]:
#Maximum AUC score on test set VS max_depth, min_samples_split

plt.rcParams["figure.figsize"] = (10, 7)


title = 'Maximum AUC score on test set VS max_depth, min_samples_split'

sns.heatmap(max_scores.mean_test_score, annot=True, fmt='.4g');
plt.title(title);

Best Train Model using best Hyper parameter

In [70]:
from sklearn.metrics import roc_curve, auc
from sklearn.tree import DecisionTreeClassifier

dt = DecisionTreeClassifier(max_depth = 10, min_samples_split = 500,class_weight='balanced')

clf = dt.fit(X_train_merge, Y_train)

y_train_pred = dt.predict_proba(X_train_merge)[:,1]    
y_test_pred = dt.predict_proba(X_test_merge)[:,1]

train_fpr, train_tpr, tr_thresholds = roc_curve(Y_train, y_train_pred)
test_fpr, test_tpr, te_thresholds = roc_curve(Y_test, y_test_pred)

plt.plot(train_fpr, train_tpr, label="Train AUC ="+str(auc(train_fpr, train_tpr)))
plt.plot(test_fpr, test_tpr, label="Test AUC ="+str(auc(test_fpr, test_tpr)))
plt.legend()
plt.xlabel("True Positive Rate(TPR)")
plt.ylabel("False Positive Rate(FPR)")
plt.title("AUC")
plt.grid(True)
plt.show()
In [71]:
a = vectorizer_categories.get_feature_names()
b = vectorizer_sub_cat.get_feature_names()
c = vectorizer_school_state.get_feature_names()
d = vectorizer_project_grade_cat.get_feature_names()
e = vectorizer_teacher_prefix_cat.get_feature_names()
f = vectorizer_title_tfidf.get_feature_names()
g = vectorizer_essay_tfidf.get_feature_names()
In [72]:
from itertools import chain 

feature_names_bow = list(chain(
a,
b,
c,
d,
e,
["Price","Quantity","Prec_no_projts"],
f,
g))
In [73]:
len(feature_names_bow)
Out[73]:
5483
In [74]:
import os     

os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'

from sklearn.tree import DecisionTreeClassifier
dt = DecisionTreeClassifier(max_depth=3)

clf = dt.fit(X_train_merge,Y_train)

import graphviz
from sklearn import tree
from graphviz import Source

dt_data = tree.export_graphviz(dt, out_file=None, feature_names=feature_names_bow)
graph = graphviz.Source(dt_data) 
graph.render("Bow tree_set1",view = True)
Out[74]:
'Bow tree_set1.pdf'

Confusion Matrix

In [74]:
def predict(proba, threshould, fpr, tpr):
    
    t = threshould[np.argmax(tpr*(1-fpr))]
        
    print("the maximum value of tpr*(1-fpr)", max(tpr*(1-fpr)), "for threshold", np.round(t,3))
    predictions = []
    for i in proba:
        if i>=t:
            predictions.append(1)
        else:
            predictions.append(0)
    return predictions
In [76]:
print("="*100)
from sklearn.metrics import confusion_matrix
print("Train confusion matrix")
print(confusion_matrix(Y_train, predict(y_train_pred, tr_thresholds, train_fpr, train_tpr)))
print("="*100)
print("Test confusion matrix")
print(confusion_matrix(Y_test, predict(y_test_pred, tr_thresholds, test_fpr, test_tpr)))
print("="*100)
====================================================================================================
Train confusion matrix
the maximum value of tpr*(1-fpr) 0.31766458659297314 for threshold 0.539
[[1758  661]
 [7482 5810]]
====================================================================================================
Test confusion matrix
the maximum value of tpr*(1-fpr) 0.3143781710053333 for threshold 0.539
[[1240  538]
 [5367 4405]]
====================================================================================================

Confusion Matrix -Heat map - Train

In [77]:
conf_mat_BOW_train = pd.DataFrame(confusion_matrix(Y_train, predict(y_train_pred, tr_thresholds, train_fpr, train_tpr)), range(2),range(2))
sns.set(font_scale=1.4)
sns.heatmap(conf_mat_BOW_train, annot=True,annot_kws={"size": 16}, fmt='g')
plt.xlabel("Predicted Label")
plt.ylabel("Actual Label")
the maximum value of tpr*(1-fpr) 0.31766458659297314 for threshold 0.539
Out[77]:
Text(62.5, 0.5, 'Actual Label')

Confusion Matrix -Heat map - Test

In [78]:
conf_mat_BOW_test= pd.DataFrame(confusion_matrix(Y_test, predict(y_test_pred, tr_thresholds, test_fpr, test_fpr)), range(2),range(2))
sns.set(font_scale=1.4)
sns.heatmap(conf_mat_BOW_test, annot=True,annot_kws={"size": 16}, fmt='g')
plt.xlabel("Predicted Label")
plt.ylabel("Actual Label")
the maximum value of tpr*(1-fpr) 0.2110281771583951 for threshold 0.539
Out[78]:
Text(62.5, 0.5, 'Actual Label')

False Positive datapoints from the BOW

In [79]:
import numpy as np

fp_rows = []
y_train_label = []


for i in range(len(y_train_pred)):
    if (y_train_pred[i] >= 0.562): 
        
        y_train_label.append(1)
        
        if (Y_train[i] == 0 and y_train_label[i] == 1):
        
            fp_rows.append(i)
    else:
        y_train_label.append(0)
In [80]:
tp_freq = {}

df_bow = pd.DataFrame(X_train_merge.todense())
df_bow_fp = df_bow.iloc[fp_rows,:]
df_bow_fp.columns = feature_names_bow
tp_freq = (df_bow_fp.sum()).to_dict()

Wordcloud of the false positive datapoints

In [81]:
##https://www.tutorialspoint.com/create-word-cloud-using-python
from wordcloud import WordCloud

wordcloud = WordCloud(width = 1000, height = 500, background_color ='white').generate_from_frequencies(tp_freq)
plt.figure(figsize=(25,10))
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
plt.close()

Box plot on the false positive

In [82]:
X_train['price'][fp_rows]
plt.boxplot(X_train['price'][fp_rows])
plt.title('Plot the box plot with the `price` of these `false positive data points')
plt.xlabel('Rejected projects')
plt.ylabel('Price')
plt.grid(True)
plt.show()

Pdf with the teacher_number_of_previously_posted_projects of these false positive data points

In [83]:
X_train['teacher_number_of_previously_posted_projects'][fp_rows]
plt.figure(figsize=(15,5))
sns.distplot(X_train['teacher_number_of_previously_posted_projects'][fp_rows], hist=False, label="False Positive points")
plt.title('Pdf with the teacher_number_of_previously_posted_projects of these false positive data points')
plt.xlabel('Teacher_number_of_previously_posted_projects')
plt.ylabel('Likelyhood')
plt.legend()
plt.show()

SET 2

Applying Decision trees on TFIDF

In [66]:
from scipy.sparse import hstack

X_train_merge = hstack((categories_one_hot_train, sub_cat_one_hot_train, school_state_one_hot_train, project_grade_cat_one_hot_train, teacher_prefix_cat_one_hot_train, price_data_train, quant_train, prev_no_projects_train,title_tfidf_train, essay_tfidf_train)).tocsr()
X_test_merge = hstack((categories_one_hot_test, sub_cat_one_hot_test, school_state_one_hot_test, project_grade_cat_one_hot_test, teacher_prefix_cat_one_hot_test, price_data_test, quant_test, prev_no_projects_test,title_tfidf_test, essay_tfidf_test)).tocsr()

print("Final Data matrix")
print("="*100)
print(X_train_merge.shape, Y_train.shape)
print(X_test_merge.shape, Y_test.shape)
print("="*100)
Final Data matrix
====================================================================================================
(17956, 5594) (17956,)
(13200, 5594) (13200,)
====================================================================================================

Best hyper parameter using the ROC/AUC higest value and K-fold cross validation.

In [73]:
def batch_predict(clf, data):
    # roc_auc_score(y_true, y_score) the 2nd parameter should be probability estimates of the positive class
    # not the predicted outputs

    y_data_pred = []
    tr_loop = data.shape[0] - data.shape[0]%1000
    # consider you X_tr shape is 49041, then your cr_loop will be 49041 - 49041%1000 = 49000
    # in this for loop we will iterate unti the last 1000 multiplier
    for i in range(0, tr_loop, 1000):
        y_data_pred.extend(clf.predict_proba(data[i:i+1000])[:,1])
    # we will be predicting for the last data points
    y_data_pred.extend(clf.predict_proba(data[tr_loop:])[:,1])
    
    return y_data_pred
In [ ]:
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier

dt = DecisionTreeClassifier()

parameters = {'max_depth':[1, 5, 10, 50, 100, 500], 'min_samples_split': [5, 10, 100, 500]}


clf = GridSearchCV(dt, parameters, cv= 10, scoring='roc_auc')

clf.fit(X_train_merge,Y_train)

train_auc= clf.cv_results_['mean_train_score']
train_auc_std= clf.cv_results_['std_train_score']
cv_auc = clf.cv_results_['mean_test_score'] 
cv_auc_std= clf.cv_results_['std_test_score']
parm_max_depth = clf.cv_results_['param_max_depth']
param_min_samples_split = clf.cv_results_['param_min_samples_split']

Heatmap for the hyperparameters

In [89]:
#https://towardsdatascience.com/using-3d-visualizations-to-tune-hyperparameters-of-ml-models-with-python-ba2885eab2e9

df_gridsearch = pd.DataFrame(clf.cv_results_)

#Maximum AUC score on train set VS max_depth, min_samples_split
max_scores = df_gridsearch.groupby(['param_max_depth',
                                    'param_min_samples_split']).max().unstack()[['mean_test_score', 'mean_train_score']]
plt.rcParams["figure.figsize"] = (10, 7)

title = 'Maximum AUC score on train set VS max_depth, min_samples_split'

sns.heatmap(max_scores.mean_train_score, annot=True, fmt='.4g');
plt.title(title);
In [90]:
#Maximum AUC score on test set VS max_depth, min_samples_split

plt.rcParams["figure.figsize"] = (10, 7)


title = 'Maximum AUC score on test set VS max_depth, min_samples_split'

sns.heatmap(max_scores.mean_test_score, annot=True, fmt='.4g');
plt.title(title);

Best Train Model using best Hyper parameter

In [68]:
from sklearn.metrics import roc_curve, auc
from sklearn.tree import DecisionTreeClassifier

dt = DecisionTreeClassifier(max_depth = 50, min_samples_split = 500,class_weight='balanced')

clf = dt.fit(X_train_merge, Y_train)

y_train_pred = dt.predict_proba(X_train_merge)[:,1]    
y_test_pred = dt.predict_proba(X_test_merge)[:,1]

train_fpr, train_tpr, tr_thresholds = roc_curve(Y_train, y_train_pred)
test_fpr, test_tpr, te_thresholds = roc_curve(Y_test, y_test_pred)

plt.plot(train_fpr, train_tpr, label="Train AUC ="+str(auc(train_fpr, train_tpr)))
plt.plot(test_fpr, test_tpr, label="Test AUC ="+str(auc(test_fpr, test_tpr)))
plt.legend()
plt.xlabel("True Positive Rate(TPR)")
plt.ylabel("False Positive Rate(FPR)")
plt.title("AUC")
plt.grid(True)
plt.show()
In [69]:
a = vectorizer_categories.get_feature_names()
b = vectorizer_sub_cat.get_feature_names()
c = vectorizer_school_state.get_feature_names()
d = vectorizer_project_grade_cat.get_feature_names()
e = vectorizer_teacher_prefix_cat.get_feature_names()
f = vectorizer_title_tfidf.get_feature_names()
g = vectorizer_essay_tfidf.get_feature_names()
In [70]:
from itertools import chain 

feature_names_tfidf = list(chain(
a,
b,
c,
d,
e,
["Price","Quantity","Prec_no_projts"],
f,
g))
In [71]:
import os     

os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'

from sklearn.tree import DecisionTreeClassifier
dt = DecisionTreeClassifier(max_depth=3)

clf = dt.fit(X_train_merge,Y_train)

import graphviz
from sklearn import tree
from graphviz import Source

dt_data = tree.export_graphviz(dt, out_file=None, feature_names=feature_names_tfidf)
graph = graphviz.Source(dt_data) 
graph.render("Bow tree_set2",view = True)
Out[71]:
'Bow tree_set2.pdf'

Confusion Matrix

In [75]:
print("="*100)
from sklearn.metrics import confusion_matrix
print("Train confusion matrix")
print(confusion_matrix(Y_train, predict(y_train_pred, tr_thresholds, train_fpr, train_fpr)))
print("="*100)
print("Test confusion matrix")
print(confusion_matrix(Y_test, predict(y_test_pred, tr_thresholds, test_fpr, test_fpr)))
print("="*100)
====================================================================================================
Train confusion matrix
the maximum value of tpr*(1-fpr) 0.24998425296044344 for threshold 0.369
[[ 1397  1375]
 [ 2540 12644]]
====================================================================================================
Test confusion matrix
the maximum value of tpr*(1-fpr) 0.2351176769287089 for threshold 0.46
[[1267  770]
 [5856 5307]]
====================================================================================================
In [76]:
# heat map for train data
conf_matr_df_tfidf_train = pd.DataFrame(confusion_matrix(Y_train, predict(y_train_pred, tr_thresholds, train_fpr, train_fpr)), range(2),range(2))
sns.set(font_scale=1.4)
sns.heatmap(conf_matr_df_tfidf_train, annot=True,annot_kws={"size": 16}, fmt='g')
plt.xlabel("Predicted Label")
plt.ylabel("Actual Label")
the maximum value of tpr*(1-fpr) 0.24998425296044344 for threshold 0.369
Out[76]:
Text(26.5, 0.5, 'Actual Label')
In [77]:
#Heat map for test data

conf_matr_df_tfidf_test = pd.DataFrame(confusion_matrix(Y_test, predict(y_test_pred, tr_thresholds, test_fpr, test_fpr)), range(2),range(2))
sns.set(font_scale=1.4)
sns.heatmap(conf_matr_df_tfidf_test, annot=True,annot_kws={"size": 16}, fmt='g')
plt.xlabel("Predicted Label")
plt.ylabel("Actual Label")
the maximum value of tpr*(1-fpr) 0.2351176769287089 for threshold 0.46
Out[77]:
Text(26.5, 0.5, 'Actual Label')

Word cloud for the false positive points

In [79]:
import numpy as np

fp_rows = []
y_train_label = []


for i in range(len(y_train_pred)):
    if (y_train_pred[i] >= 0.349): 
        
        y_train_label.append(1)
        
        if (Y_train[i] == 0 and y_train_label[i] == 1):
        
            fp_rows.append(i)
    else:
        y_train_label.append(0)

tp_freq = {}

df_tfidf = pd.DataFrame(X_train_merge.todense())
df_tfidf_fp = df_tfidf.iloc[fp_rows,:]
df_tfidf_fp.columns = feature_names_tfidf
df_tfidf_fp.head(3)

tp_freq = (df_tfidf_fp.sum()).to_dict()
In [80]:
from wordcloud import WordCloud
##https://www.tutorialspoint.com/create-word-cloud-using-python

wordcloud = WordCloud(width = 1000, height = 500, background_color ='white').generate_from_frequencies(tp_freq)
plt.figure(figsize=(25,10))
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
plt.close()

Box Plot for the false positive points of the PRICE

In [81]:
X_train['price'][fp_rows]
plt.boxplot(X_train['price'][fp_rows])
plt.title('Plot the box plot with the `price` of these `false positive data points')
plt.xlabel('Rejected projects')
plt.ylabel('Price')
plt.grid(True)
plt.show()

PDF with the teacher_number_of_previously_posted_projects of these false positive data points

In [82]:
X_train['teacher_number_of_previously_posted_projects'][fp_rows]
plt.figure(figsize=(15,5))
sns.distplot(X_train['teacher_number_of_previously_posted_projects'][fp_rows], hist=False, label="False Positive points")
plt.title('Pdf with the teacher_number_of_previously_posted_projects of these false positive data points')
plt.xlabel('Teacher_number_of_previously_posted_projects')
plt.ylabel('Likelyhood')
plt.legend()
plt.show()

SET 3

Applying Decision trees on AVG W2V

In [83]:
from scipy.sparse import hstack

X_train_merge = hstack((categories_one_hot_train, sub_cat_one_hot_train, school_state_one_hot_train, project_grade_cat_one_hot_train, teacher_prefix_cat_one_hot_train, price_data_train, quant_train, prev_no_projects_train,title_avg_w2v_train, essay_avg_w2v_train)).tocsr()
X_test_merge = hstack((categories_one_hot_test, sub_cat_one_hot_test, school_state_one_hot_test, project_grade_cat_one_hot_test, teacher_prefix_cat_one_hot_test, price_data_test, quant_test, prev_no_projects_test,title_avg_w2v_test, essay_avg_w2v_test)).tocsr()

print("Final Data matrix")
print("="*100)
print(X_train_merge.shape, Y_train.shape)
print(X_test_merge.shape, Y_test.shape)
print("="*100)
Final Data matrix
====================================================================================================
(17956, 703) (17956,)
(13200, 703) (13200,)
====================================================================================================

Best hyper parameter using the ROC/AUC higest value and K-fold cross validation.

In [115]:
def batch_predict(clf, data):
    # roc_auc_score(y_true, y_score) the 2nd parameter should be probability estimates of the positive class
    # not the predicted outputs

    y_data_pred = []
    tr_loop = data.shape[0] - data.shape[0]%1000
    # consider you X_tr shape is 49041, then your cr_loop will be 49041 - 49041%1000 = 49000
    # in this for loop we will iterate unti the last 1000 multiplier
    for i in range(0, tr_loop, 1000):
        y_data_pred.extend(clf.predict_proba(data[i:i+1000])[:,1])
    # we will be predicting for the last data points
    y_data_pred.extend(clf.predict_proba(data[tr_loop:])[:,1])
    
    return y_data_pred
In [ ]:
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier

dt = DecisionTreeClassifier()

parameters = {'max_depth':[1, 5, 10, 50, 100, 500], 'min_samples_split': [5, 10, 100, 500]}


clf = GridSearchCV(dt, parameters, cv= 10, scoring='roc_auc')

clf.fit(X_train_merge,Y_train)

train_auc= clf.cv_results_['mean_train_score']
train_auc_std= clf.cv_results_['std_train_score']
cv_auc = clf.cv_results_['mean_test_score'] 
cv_auc_std= clf.cv_results_['std_test_score']
parm_max_depth = clf.cv_results_['param_max_depth']
param_min_samples_split = clf.cv_results_['param_min_samples_split']

Heatmap for the hyperparameters

In [117]:
#https://towardsdatascience.com/using-3d-visualizations-to-tune-hyperparameters-of-ml-models-with-python-ba2885eab2e9

df_gridsearch = pd.DataFrame(clf.cv_results_)

#Maximum AUC score on train set VS max_depth, min_samples_split
max_scores = df_gridsearch.groupby(['param_max_depth',
                                    'param_min_samples_split']).max().unstack()[['mean_test_score', 'mean_train_score']]
plt.rcParams["figure.figsize"] = (10, 7)

title = 'Maximum AUC score on train set VS max_depth, min_samples_split'

sns.heatmap(max_scores.mean_train_score, annot=True, fmt='.4g');
plt.title(title);
In [118]:
#Maximum AUC score on test set VS max_depth, min_samples_split

plt.rcParams["figure.figsize"] = (10, 7)


title = 'Maximum AUC score on test set VS max_depth, min_samples_split'

sns.heatmap(max_scores.mean_test_score, annot=True, fmt='.4g');
plt.title(title);

Best Train Model using best Hyper parameter

In [119]:
from sklearn.metrics import roc_curve, auc
from sklearn.tree import DecisionTreeClassifier

dt = DecisionTreeClassifier(max_depth = 5, min_samples_split = 10,class_weight='balanced')

clf = dt.fit(X_train_merge, Y_train)

y_train_pred = dt.predict_proba(X_train_merge)[:,1]    
y_test_pred = dt.predict_proba(X_test_merge)[:,1]

train_fpr, train_tpr, tr_thresholds = roc_curve(Y_train, y_train_pred)
test_fpr, test_tpr, te_thresholds = roc_curve(Y_test, y_test_pred)

plt.plot(train_fpr, train_tpr, label="Train AUC ="+str(auc(train_fpr, train_tpr)))
plt.plot(test_fpr, test_tpr, label="Test AUC ="+str(auc(test_fpr, test_tpr)))
plt.legend()
plt.xlabel("True Positive Rate(TPR)")
plt.ylabel("False Positive Rate(FPR)")
plt.title("AUC")
plt.grid(True)
plt.show()

Confusion Matrix

In [125]:
print("="*100)
from sklearn.metrics import confusion_matrix
print("Train confusion matrix")
print(confusion_matrix(Y_train, predict(y_train_pred, tr_thresholds, train_fpr, train_fpr)))
print("="*100)
print("Test confusion matrix")
print(confusion_matrix(Y_test, predict(y_test_pred, tr_thresholds, test_fpr, test_fpr)))
print("="*100)
====================================================================================================
Train confusion matrix
the maximum value of tpr*(1-fpr) 0.24997329772346216 for threshold 0.404
[[1197 1222]
 [3372 9920]]
====================================================================================================
Test confusion matrix
the maximum value of tpr*(1-fpr) 0.24969600959610083 for threshold 0.483
[[ 858  920]
 [3335 6437]]
====================================================================================================
In [126]:
# heat map for train data
conf_matr_df_tfidf_train = pd.DataFrame(confusion_matrix(Y_train, predict(y_train_pred, tr_thresholds, train_fpr, train_fpr)), range(2),range(2))
sns.set(font_scale=1.4)
sns.heatmap(conf_matr_df_tfidf_train, annot=True,annot_kws={"size": 16}, fmt='g')
plt.xlabel("Predicted Label")
plt.ylabel("Actual Label")
the maximum value of tpr*(1-fpr) 0.24997329772346216 for threshold 0.404
Out[126]:
Text(62.5, 0.5, 'Actual Label')
In [127]:
#Heat map for test data

conf_matr_df_tfidf_test = pd.DataFrame(confusion_matrix(Y_test, predict(y_test_pred, tr_thresholds, test_fpr, test_fpr)), range(2),range(2))
sns.set(font_scale=1.4)
sns.heatmap(conf_matr_df_tfidf_test, annot=True,annot_kws={"size": 16}, fmt='g')
plt.xlabel("Predicted Label")
plt.ylabel("Actual Label")
the maximum value of tpr*(1-fpr) 0.24969600959610083 for threshold 0.483
Out[127]:
Text(62.5, 0.5, 'Actual Label')

SET 4

Applying Decision trees on TFIDF W2V

In [84]:
from scipy.sparse import hstack

X_train_merge = hstack((categories_one_hot_train, sub_cat_one_hot_train, school_state_one_hot_train, project_grade_cat_one_hot_train, teacher_prefix_cat_one_hot_train, price_data_train, quant_train, prev_no_projects_train,title_tfidf_w2v_train, essay_tfidf_w2v_train)).tocsr()
X_test_merge = hstack((categories_one_hot_test, sub_cat_one_hot_test, school_state_one_hot_test, project_grade_cat_one_hot_test, teacher_prefix_cat_one_hot_test, price_data_test, quant_test, prev_no_projects_test,title_tfidf_w2v_test, essay_tfidf_w2v_test)).tocsr()

print("Final Data matrix")
print("="*100)
print(X_train_merge.shape, Y_train.shape)
print(X_test_merge.shape, Y_test.shape)
print("="*100)
Final Data matrix
====================================================================================================
(17956, 703) (17956,)
(13200, 703) (13200,)
====================================================================================================

Best hyper parameter using the ROC/AUC higest value and K-fold cross validation.

In [130]:
def batch_predict(clf, data):
    # roc_auc_score(y_true, y_score) the 2nd parameter should be probability estimates of the positive class
    # not the predicted outputs

    y_data_pred = []
    tr_loop = data.shape[0] - data.shape[0]%1000
    # consider you X_tr shape is 49041, then your cr_loop will be 49041 - 49041%1000 = 49000
    # in this for loop we will iterate unti the last 1000 multiplier
    for i in range(0, tr_loop, 1000):
        y_data_pred.extend(clf.predict_proba(data[i:i+1000])[:,1])
    # we will be predicting for the last data points
    y_data_pred.extend(clf.predict_proba(data[tr_loop:])[:,1])
    
    return y_data_pred
In [ ]:
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier

dt = DecisionTreeClassifier()

parameters = {'max_depth':[1, 5, 10, 50, 100, 500], 'min_samples_split': [5, 10, 100, 500]}


clf = GridSearchCV(dt, parameters, cv= 10, scoring='roc_auc')

clf.fit(X_train_merge,Y_train)

train_auc= clf.cv_results_['mean_train_score']
train_auc_std= clf.cv_results_['std_train_score']
cv_auc = clf.cv_results_['mean_test_score'] 
cv_auc_std= clf.cv_results_['std_test_score']
parm_max_depth = clf.cv_results_['param_max_depth']
param_min_samples_split = clf.cv_results_['param_min_samples_split']

Heatmap for the hyperparameters

In [132]:
#https://towardsdatascience.com/using-3d-visualizations-to-tune-hyperparameters-of-ml-models-with-python-ba2885eab2e9

df_gridsearch = pd.DataFrame(clf.cv_results_)

#Maximum AUC score on train set VS max_depth, min_samples_split
max_scores = df_gridsearch.groupby(['param_max_depth',
                                    'param_min_samples_split']).max().unstack()[['mean_test_score', 'mean_train_score']]
plt.rcParams["figure.figsize"] = (10, 7)

title = 'Maximum AUC score on train set VS max_depth, min_samples_split'

sns.heatmap(max_scores.mean_train_score, annot=True, fmt='.4g');
plt.title(title);
In [133]:
#Maximum AUC score on test set VS max_depth, min_samples_split

plt.rcParams["figure.figsize"] = (10, 7)


title = 'Maximum AUC score on test set VS max_depth, min_samples_split'

sns.heatmap(max_scores.mean_test_score, annot=True, fmt='.4g');
plt.title(title);

Best Train Model using best Hyper parameter

In [134]:
from sklearn.metrics import roc_curve, auc
from sklearn.tree import DecisionTreeClassifier

dt = DecisionTreeClassifier(max_depth = 5, min_samples_split = 5,class_weight='balanced')

clf = dt.fit(X_train_merge, Y_train)

y_train_pred = dt.predict_proba(X_train_merge)[:,1]    
y_test_pred = dt.predict_proba(X_test_merge)[:,1]

train_fpr, train_tpr, tr_thresholds = roc_curve(Y_train, y_train_pred)
test_fpr, test_tpr, te_thresholds = roc_curve(Y_test, y_test_pred)

plt.plot(train_fpr, train_tpr, label="Train AUC ="+str(auc(train_fpr, train_tpr)))
plt.plot(test_fpr, test_tpr, label="Test AUC ="+str(auc(test_fpr, test_tpr)))
plt.legend()
plt.xlabel("True Positive Rate(TPR)")
plt.ylabel("False Positive Rate(FPR)")
plt.title("AUC")
plt.grid(True)
plt.show()

Confusion Matrix

In [135]:
print("="*100)
from sklearn.metrics import confusion_matrix
print("Train confusion matrix")
print(confusion_matrix(Y_train, predict(y_train_pred, tr_thresholds, train_fpr, train_fpr)))
print("="*100)
print("Test confusion matrix")
print(confusion_matrix(Y_test, predict(y_test_pred, tr_thresholds, test_fpr, test_fpr)))
print("="*100)
====================================================================================================
Train confusion matrix
the maximum value of tpr*(1-fpr) 0.21070787777825437 for threshold 0.477
[[  730  1689]
 [ 3030 10262]]
====================================================================================================
Test confusion matrix
the maximum value of tpr*(1-fpr) 0.21278442556885113 for threshold 0.536
[[1232  546]
 [5770 4002]]
====================================================================================================
In [136]:
# heat map for train data
conf_matr_df_tfidf_train = pd.DataFrame(confusion_matrix(Y_train, predict(y_train_pred, tr_thresholds, train_fpr, train_fpr)), range(2),range(2))
sns.set(font_scale=1.4)
sns.heatmap(conf_matr_df_tfidf_train, annot=True,annot_kws={"size": 16}, fmt='g')
plt.xlabel("Predicted Label")
plt.ylabel("Actual Label")
the maximum value of tpr*(1-fpr) 0.21070787777825437 for threshold 0.477
Out[136]:
Text(62.5, 0.5, 'Actual Label')
In [137]:
#Heat map for test data

conf_matr_df_tfidf_test = pd.DataFrame(confusion_matrix(Y_test, predict(y_test_pred, tr_thresholds, test_fpr, test_fpr)), range(2),range(2))
sns.set(font_scale=1.4)
sns.heatmap(conf_matr_df_tfidf_test, annot=True,annot_kws={"size": 16}, fmt='g')
plt.xlabel("Predicted Label")
plt.ylabel("Actual Label")
the maximum value of tpr*(1-fpr) 0.21278442556885113 for threshold 0.536
Out[137]:
Text(62.5, 0.5, 'Actual Label')

Task 2

In [85]:
from scipy.sparse import hstack

X_train_merge = hstack((categories_one_hot_train, sub_cat_one_hot_train, school_state_one_hot_train, project_grade_cat_one_hot_train, teacher_prefix_cat_one_hot_train, price_data_train, quant_train, prev_no_projects_train,title_tfidf_train, essay_tfidf_train)).tocsr()
X_test_merge = hstack((categories_one_hot_test, sub_cat_one_hot_test, school_state_one_hot_test, project_grade_cat_one_hot_test, teacher_prefix_cat_one_hot_test, price_data_test, quant_test, prev_no_projects_test,title_tfidf_test, essay_tfidf_test)).tocsr()

print("Final Data matrix")
print("="*100)
print(X_train_merge.shape, Y_train.shape)
print(X_test_merge.shape, Y_test.shape)
print("="*100)
Final Data matrix
====================================================================================================
(17956, 5594) (17956,)
(13200, 5594) (13200,)
====================================================================================================
In [86]:
#https://scikit-learn.org/stable/modules/feature_selection.html

from sklearn.ensemble import ExtraTreesClassifier
import pandas as pd

clf = ExtraTreesClassifier()

df_tfidf_5k = pd.DataFrame(X_train_merge.todense())
df_tfidf_5k.columns = feature_names_tfidf

clf = clf.fit(df_tfidf_5k,Y_train)
In [87]:
# https://datascience.stackexchange.com/questions/31406/tree-decisiontree-feature-importances-numbers-correspond-to-how-features

tfidf_5k_fimpt = {}
tfidf_5k_fimpt = dict(zip(feature_names_tfidf, clf.feature_importances_))
#https://stackoverflow.com/questions/16772071/sort-dict-by-value-python
tfidf_5k_fimpt = sorted(tfidf_5k_fimpt.items(), key=lambda x: x[1], reverse=True)

tfidf_5k_fimpt = tfidf_5k_fimpt[:5000]
#https://stackoverflow.com/questions/22412258/get-the-first-element-of-each-tuple-in-a-list-in-python


tfidf_5k_fimpt = [ seq[0] for seq in tfidf_5k_fimpt if seq[1] > 0.0 ] # choosing features greater than 0
df_tfidf_5k = df_tfidf_5k[tfidf_5k_fimpt]


df_5k_test = pd.DataFrame(X_test_merge.todense(),columns = feature_names_tfidf)

df_5k_test = df_5k_test[tfidf_5k_fimpt]

Best hyper parameter using the ROC/AUC higest value and K-fold cross validation.

In [88]:
def batch_predict(clf, data):
    # roc_auc_score(y_true, y_score) the 2nd parameter should be probability estimates of the positive class
    # not the predicted outputs

    y_data_pred = []
    tr_loop = data.shape[0] - data.shape[0]%1000
    # consider you X_tr shape is 49041, then your cr_loop will be 49041 - 49041%1000 = 49000
    # in this for loop we will iterate unti the last 1000 multiplier
    for i in range(0, tr_loop, 1000):
        y_data_pred.extend(clf.predict_proba(data[i:i+1000])[:,1])
    # we will be predicting for the last data points
    y_data_pred.extend(clf.predict_proba(data[tr_loop:])[:,1])
    
    return y_data_pred
In [ ]:
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier

dt = DecisionTreeClassifier()

parameters = {'max_depth':[1, 5, 10, 50, 100, 500], 'min_samples_split': [5, 10, 100, 500]}


clf = GridSearchCV(dt, parameters, cv= 10, scoring='roc_auc')

clf.fit(df_tfidf_5k,Y_train)

train_auc= clf.cv_results_['mean_train_score']
train_auc_std= clf.cv_results_['std_train_score']
cv_auc = clf.cv_results_['mean_test_score'] 
cv_auc_std= clf.cv_results_['std_test_score']
parm_max_depth = clf.cv_results_['param_max_depth']
param_min_samples_split = clf.cv_results_['param_min_samples_split']

Heatmap for the hyperparameters

In [146]:
#https://towardsdatascience.com/using-3d-visualizations-to-tune-hyperparameters-of-ml-models-with-python-ba2885eab2e9

df_gridsearch = pd.DataFrame(clf.cv_results_)

#Maximum AUC score on train set VS max_depth, min_samples_split
max_scores = df_gridsearch.groupby(['param_max_depth',
                                    'param_min_samples_split']).max().unstack()[['mean_test_score', 'mean_train_score']]
plt.rcParams["figure.figsize"] = (10, 7)

title = 'Maximum AUC score on train set VS max_depth, min_samples_split'

sns.heatmap(max_scores.mean_train_score, annot=True, fmt='.4g');
plt.title(title);
In [147]:
#Maximum AUC score on test set VS max_depth, min_samples_split

plt.rcParams["figure.figsize"] = (10, 7)


title = 'Maximum AUC score on test set VS max_depth, min_samples_split'

sns.heatmap(max_scores.mean_test_score, annot=True, fmt='.4g');
plt.title(title);

Best Train Model using best Hyper parameter

In [89]:
from sklearn.metrics import roc_curve, auc
from sklearn.tree import DecisionTreeClassifier

dt = DecisionTreeClassifier(max_depth = 50, min_samples_split = 500,class_weight='balanced')

clf = dt.fit(df_tfidf_5k, Y_train)

y_train_pred = dt.predict_proba(df_tfidf_5k)[:,1]    
y_test_pred = dt.predict_proba(df_5k_test)[:,1]

train_fpr, train_tpr, tr_thresholds = roc_curve(Y_train, y_train_pred)
test_fpr, test_tpr, te_thresholds = roc_curve(Y_test, y_test_pred)

plt.plot(train_fpr, train_tpr, label="Train AUC ="+str(auc(train_fpr, train_tpr)))
plt.plot(test_fpr, test_tpr, label="Test AUC ="+str(auc(test_fpr, test_tpr)))
plt.legend()
plt.xlabel("True Positive Rate(TPR)")
plt.ylabel("False Positive Rate(FPR)")
plt.title("AUC")
plt.grid(True)
plt.show()

Confusion Matrix

In [90]:
def predict(proba, threshould, fpr, tpr):
    
    t = threshould[np.argmax(tpr*(1-fpr))]
        
    print("the maximum value of tpr*(1-fpr)", max(tpr*(1-fpr)), "for threshold", np.round(t,3))
    predictions = []
    for i in proba:
        if i>=t:
            predictions.append(1)
        else:
            predictions.append(0)
    return predictions
In [91]:
print("="*100)
from sklearn.metrics import confusion_matrix
print("Train confusion matrix")
print(confusion_matrix(Y_train, predict(y_train_pred, tr_thresholds, train_fpr, train_tpr)))
print("="*100)
print("Test confusion matrix")
print(confusion_matrix(Y_test, predict(y_test_pred, tr_thresholds, test_fpr, test_tpr)))
print("="*100)
====================================================================================================
Train confusion matrix
the maximum value of tpr*(1-fpr) 0.46727392660611844 for threshold 0.46
[[2426  346]
 [7077 8107]]
====================================================================================================
Test confusion matrix
the maximum value of tpr*(1-fpr) 0.3006093795289694 for threshold 0.46
[[1257  780]
 [5725 5438]]
====================================================================================================

Confusion Matrix -Heat map - Train

In [92]:
conf_mat_BOW_train = pd.DataFrame(confusion_matrix(Y_train, predict(y_train_pred, tr_thresholds, train_fpr, train_tpr)), range(2),range(2))
sns.set(font_scale=1.4)
sns.heatmap(conf_mat_BOW_train, annot=True,annot_kws={"size": 16}, fmt='g')
plt.xlabel("Predicted Label")
plt.ylabel("Actual Label")
the maximum value of tpr*(1-fpr) 0.46727392660611844 for threshold 0.46
Out[92]:
Text(26.5, 0.5, 'Actual Label')

Confusion Matrix -Heat map - Test

In [93]:
conf_mat_BOW_test= pd.DataFrame(confusion_matrix(Y_test, predict(y_test_pred, tr_thresholds, test_fpr, test_fpr)), range(2),range(2))
sns.set(font_scale=1.4)
sns.heatmap(conf_mat_BOW_test, annot=True,annot_kws={"size": 16}, fmt='g')
plt.xlabel("Predicted Label")
plt.ylabel("Actual Label")
the maximum value of tpr*(1-fpr) 0.23629134935938456 for threshold 0.46
Out[93]:
Text(26.5, 0.5, 'Actual Label')

Conclusion

In [94]:
from prettytable import PrettyTable

x_pretty_table = PrettyTable()
x_pretty_table.field_names = ["Model Type","Vectorizer","max_depth","min_sample_split","Train-AUC","Test-AUC"]

x_pretty_table.add_row(["Decision Tree","BOW",10,500,0.62,0.60])
x_pretty_table.add_row([ "Decision Tree","TFIDF",50,500,0.78, 0.56])
x_pretty_table.add_row([ "Decision Tree","AVG W2V",5,10,0.68,0.58])
x_pretty_table.add_row([ "Decision Tree","TFIDF W2V",5,5,0.57,0.56])
x_pretty_table.add_row([ "Decision Tree :Top 5k Features","TFIDF",50,500,0.78,0.56])

print(x_pretty_table)
+--------------------------------+------------+-----------+------------------+-----------+----------+
|           Model Type           | Vectorizer | max_depth | min_sample_split | Train-AUC | Test-AUC |
+--------------------------------+------------+-----------+------------------+-----------+----------+
|         Decision Tree          |    BOW     |     10    |       500        |    0.62   |   0.6    |
|         Decision Tree          |   TFIDF    |     50    |       500        |    0.78   |   0.56   |
|         Decision Tree          |  AVG W2V   |     5     |        10        |    0.68   |   0.58   |
|         Decision Tree          | TFIDF W2V  |     5     |        5         |    0.57   |   0.56   |
| Decision Tree :Top 5k Features |   TFIDF    |     50    |       500        |    0.78   |   0.56   |
+--------------------------------+------------+-----------+------------------+-----------+----------+
In [ ]: